码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode228 - Middle of Linked List - easy

时间:2018-08-14 14:40:38      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:color   col   实现   ret   pre   @param   hal   def   next   


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

标签:color   col   实现   ret   pre   @param   hal   def   next   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!