Middle of the Linked List

题目
Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

答案

class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null) return null;
        ListNode fast = head, slow = head;
        while(slow.next != null) {
            if(slow.next.next == null) return fast.next;
            slow = slow.next.next;
            fast = fast.next;
        }
        return fast;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • 流动的露水,腐蚀着鼻根。来自天际的长风,呼啸着穿过我的窗户。天阴阴暗暗,差一点电闪雷鸣,就可以还原曾经的悸动。人生...
    木阳洒雪阅读 233评论 0 1
  • 等着你 翠滴轻落入泥 宛若你脚步轻移 伫立窗台不肯离去 远望黑云渐渐散去 等七彩祥云飘来 我踏上北去 见你抱你 不...
    定格不留白阅读 202评论 0 0
  • 一本书、一杯茶、一首歌,一抹阳光落在脸庞,这就是我最惬意的周末时光! 读书,就像人和人之间的爱情...
    张小勇写字的地方阅读 228评论 0 3