Java Data Structures Deep Dive: Exploring Top Coding Challenges with Answers

Here are the Java code snippets for the mentioned data structure coding questions:

1. **Reverse a Linked List:**
“`java
public ListNode reverseLinkedList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
“`

2. **Two Sum:**
“`java
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target – nums[i];
if (numMap.containsKey(complement)) {
return new int[]{numMap.get(complement), i};
}
numMap.put(nums[i], i);
}
return null;
}
“`

3. **Binary Tree Inorder Traversal:**
“`java
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root != null) {
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
}
return result;
}
“`

4. **Detect a Cycle in a Linked List:**
“`java
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
“`

5. **Merge Two Sorted Lists:**
“`java
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
“`

Make sure to adapt these code snippets based on your specific requirements and the structure of your existing Java code.

Leave a Reply