简体   繁体   中英

Returning the middle node in a singly Linked List (Java)

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM