首页 > 其他 > 详细

Middle of Linked List

时间:2017-02-14 14:03:27      阅读:230      评论: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.

分析


1 value 1
1->2 value1
1->2->3 value 2
1->2->3->4 value 2
1->2->3->4->5 value 3
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * 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
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
    }
    return slow;
    }
}




Middle of Linked List

原文:http://www.cnblogs.com/zhxshseu/p/fc3825847eba7099f38805d8ec8e378e.html

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