lintcode228 - Middle of Linked List - easy


Find the middle node of a linked list.
Example
Given 1->2->3, return the node with value 2.
Given 1->2, return the node with value 1.
Challenge
If the linked list is in a data stream, can you find the middle without iterating the linked list again?

 

同向快慢指针,快挪2,慢挪1,返回慢。

 

我的实现

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param head: the head of linked list.
     * @return: a middle node of the linked list
     */
    public ListNode middleNode(ListNode head) {
        // write your code here
        if (head == null) {
            return null;
        }
        
        ListNode quick = head, slow = head;
        while (quick.next != null && quick.next.next != null) {
            quick = quick.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

 

posted @ 2018-08-14 12:01  jasminemzy  阅读(89)  评论(0编辑  收藏  举报