lintcode228 - Middle of Linked List - easy

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 







以上是关于lintcode228 - Middle of Linked List - easy的主要内容,如果未能解决你的问题,请参考以下文章

Lintcode372 Delete Node in the Middle of Singly Linked List solution 题解

Lintcode: Count of Smaller Number

LintCode: Maximum Depth of Binary Tree

lintcode-easy-Length of Last Word

lintcode-easy-Number of Islands

lintcode-easy-Maximum Depth of Binary Tree