LeetCode-142 Linked List Cycle II
来源:互联网 发布:霍金的宇宙知乎 编辑:程序博客网 时间:2024/06/01 10:52
题目描述: 给定一个链表,如果存在环,返回正向遍历环开始的节点,否则返回NULL
算法思想:
定义两个指针快指针(fast),每次向前推进2个节点;慢指针(slow),每次向前推进1个节点。约定,如果链表中存在环,当且仅当快指针首次与慢指针重合时,算法停止。也就是说,算法停止时,快指针的推进距离(DF)与慢指针的推进距离(DS)之差为一个环的长度(C), 也就是
DF−DS=C 。定义环开始节点为S, 当算法停止时,有DS=S+K ,同时,DF=2∗(S+K) , 因为快指针的推进速度是慢指针推进速度的两倍。我们推出结果为:S=C−K ,其中K表示快慢指针相遇时,指针距离环开始节点S的距离。这也就说明了,如果再推进S=C−K ,慢指针将会到达S,而与此同时,如果将链表头结点指针同时推进S=C−K ,与慢指针相遇时,此时的节点也就是环开始的节点S。算法实现:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(null == head) return null; ListNode fast = head, slow = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(fast == slow){ while(head != slow){ head = head.next; slow = slow.next; } return slow; } } return null; }}
阅读全文
0 0
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- LeetCode 142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- [leetcode 142]Linked List Cycle II
- Leetcode NO.142 Linked List Cycle II
- [leetcode]142 Linked List Cycle II
- [LeetCode 142]Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- [Leetcode 142] Linked List Cycle II
- [leetcode-142]Linked List Cycle II(c)
- leetcode 142: Linked List Cycle II
- leetCode #142 Linked List Cycle II
- Leetcode #142 Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- 【LEETCODE】142-Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- Eclipse项目如何切换成AS项目
- Boost库——signals2的用法总结
- HLS中SVD解最小二乘
- HDU 1061 Rightmost Digit
- hdu 6143 Killer Names 第二类斯特灵数 组合数学
- LeetCode-142 Linked List Cycle II
- Linux下HOOK动态链接库中API的方法
- spring
- lua读取CSV文件
- 《软件架构师的12项修炼》学习心得(二)
- 对称加密和非对称加密
- Android上的Notification
- Python中super的使用
- 【OpenCV3.3】通过透视变换矫正变形图像