首页 > 其他 > 详细

lintcode228 - Middle of Linked List - easy

时间:2018-08-14 14:06:29      阅读:216      评论:0      收藏:0      [点我收藏+]


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

原文:https://www.cnblogs.com/jasminemzy/p/9473798.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!