[leetcode][list][two pointers] Linked List Cycle II
来源:互联网 发布:matlab数据采集工具箱 编辑:程序博客网 时间:2024/05/21 08:55
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { //是否有环 if(NULL == head || NULL == head->next) return NULL; ListNode *slow = head; ListNode *fast = head->next; while(fast && fast->next && slow != fast){ slow = slow->next; fast = fast->next->next; } if(slow != fast) return NULL;//无环 //计算环中元素个数n int cnt = 1; slow = slow->next; while(slow != fast){ ++cnt; slow = slow->next; } //前后指针,一个指针先走n部,然后两个指针同步向前,相遇点就是入口 ListNode *front = head; ListNode *behind = head; for(int i = 0; i < cnt; ++i) front = front->next; while(front != behind){ front = front->next; behind = behind->next; } return front; }};
0 0
- [leetcode][list][two pointers] Linked List Cycle II
- [leetcode][list][two pointers] Linked List Cycle
- Two pointers (1) -- Linked List Cycle II, Rotate List
- [leetcode][list][two pointers] Reverse Linked List II
- LeetCode[Linked List]: Linked List Cycle II
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- Java面试问题和答案(三)
- N皇后问题
- js处理cookie详解
- 刚刚学习VC,发个程序试试
- jtable表头渲染器
- [leetcode][list][two pointers] Linked List Cycle II
- LVS DR模式中arp_ignore和arp_announce的作用解释
- html中onclick事件汇总
- Java面试问题和答案(四)
- Android开发--WIFI实现
- iOS - id && Object Messaging 深入讲解
- 让IE6 IE7 IE8 IE9 IE10 IE11支持Bootstrap的解决方法
- 自适应算法和学习算法的区别
- Ubuntu下虚拟机两种上网方式的设置:NAT和桥接方式