I've forgotten basically everything from my DSA class because I'm an idiot, so I'm spending winter break refreshing myself and doing practice problems I find online. One of them is returning the middle node in a singly Linked List. If there are two middle nodes, return the second one. The posted solution is way different from my answer and I can't figure out why mine is wrong.
My implementation is basically:
public static Integer findMiddle() {
LinkedList<Integer> list = new LinkedList();
list.add(5);
list.add(7);
list.add(11);
list.add(13);
list.add(15);
list.add(17);
return list.get(list.size()/2);
}
EDIT: Here is the given online answer:
void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
while (fast_ptr != null && fast_ptr.next != null) {
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is ["
slow_ptr.data "] \n");
}
But the online answer is a bit more complicated than that. I don't really understand why this is wrong (again, I'm an idiot). If the linked list holds Integers, I would be returning the Integer, right? What would be the benefit of returning a Node over returning the object in the list, like you would in an ArrayList?
Thank you to anyone reading this! I know this is a silly question I just don't quite understand why.
CodePudding user response:
To return the middle node in a singly linked list, you can use the following approach:
Initialize two pointers, slow and fast, to the head of the linked list. Move fast two nodes at a time, and move slow one node at a time. When fast reaches the end of the linked list, slow will be at the middle node. Return slow. Here is some sample code in Java that demonstrates this approach:
public Node findMiddleNode(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
CodePudding user response:
This question seems very much like what you're attempting to solve: https://leetcode.com/problems/middle-of-the-linked-list/
But short of seeing the exact question you're provided, the "book answer" you have is very likely assuming you don't have access to the whole list; rather, just the head (entry point) ListNode
. Which means you're going to have to traverse it to the end, and that's where the Slow & Fast Pointer technique is useful.
If we assume the question provides access to the entire LinkedList object, then your answer is fine, since you can get its size()/2
.