Given a non-empty, singly linked list with head nodehead, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

这个题也比较简单,两个pointer,一个每次向后移动一个node,另一个向后移动两个node,快的指针到链表末尾时候,慢的指针指向中间。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }

  1 2 3

 */
class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null || head.next == null)
            return head;

        ListNode p1 = head;
        ListNode p2 = head;

        while(p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }

        return p1;
    }
}

results matching ""

    No results matching ""