[LeetCode] Linked List Cycle II 链表环起始位置
2015-01-06 15:00
621 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
Hide Tags
Linked List Two Pointers
开始犯二了一点,使用了node 的val 作为判断,其实是根据内存判断。找出链表环的起始位置,这个画一下慢慢找下规律便可以:
思路:
使用快慢指针,慢指针每次前进一步,快指针每次两步
如果快慢指针相遇了,那么将快指针从标记带链表头,改为每次前进一步
当快慢指针再次相遇便是环起始位置。
这样的实现,时间很快O(n),而且空间O(1)
View Code
null.
Follow up:
Can you solve it without using extra space?
Hide Tags
Linked List Two Pointers
开始犯二了一点,使用了node 的val 作为判断,其实是根据内存判断。找出链表环的起始位置,这个画一下慢慢找下规律便可以:
思路:
使用快慢指针,慢指针每次前进一步,快指针每次两步
如果快慢指针相遇了,那么将快指针从标记带链表头,改为每次前进一步
当快慢指针再次相遇便是环起始位置。
这样的实现,时间很快O(n),而且空间O(1)
#include <iostream> using namespace std; /** * 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(head==NULL) return NULL; ListNode * fast=head,*slow=head; while(1){ if(fast->next!=NULL) fast=fast->next; else return NULL; if(fast->next!=NULL) fast=fast->next; else return NULL; slow=slow->next; if(fast==slow) break; } fast=head; while(1){ if(fast==slow) return slow; fast=fast->next; slow=slow->next; } return NULL; } }; int main() { ListNode node1(1),node2(2),node3(3),node4(4),node5(5); node1.next=&node2; node2.next=&node3; node3.next=&node4; node4.next=&node5; node5.next=&node1; Solution sol; ListNode *ret = sol.detectCycle(&node1); if(ret==NULL) cout<<"NULL"<<endl; else cout<<ret->val<<endl; return 0; }
View Code
相关文章推荐
- LeetCode Linked List Cycle II(找到带环单向链表的环起始位置)
- leetcode-Linked List Cycle II 链表判环以及求环起始位置
- [LeetCode]93. Linked List Cycle II查找链表中环的起始节点
- leetcode---linked-list-cycle-ii---链表
- LeetCode-Linked List Cycle II -有环链表-推理
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- Leetcode 链表 Linked List Cycle II
- Linked List Cycle leetcode II java (寻找链表环的入口)
- leetcode之92. Reverse Linked List II(C++读错题版本,交换一个链表中指定的两个位置上的元素)
- LeetCode刷题笔记(链表):linked-list-cycle-ii
- [Leetcode-142] Linked List Cycle II(链表有环详细分析)
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现
- LeetCode Linked List Cycle II 计算带环的链表的起点
- [LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- leetcode_c++:链表:Linked List Cycle II(142)
- [LeetCode] Linked List Cycle II 单链表中的环之二
- LeetCode之“链表”:Linked List Cycle && Linked List Cycle II
- 【leetcode】Linked List Cycle II,判断链表是否有环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环