Linked List Cycle II
来源:互联网 发布:数据港股票诊断 编辑:程序博客网 时间:2024/06/16 17:22
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?
这题是在 Linked List Cycle II 的基础上(http://blog.csdn.net/ayst123/article/details/38774927),把return true换成return findnode()即可
假设fast和slow相遇在环中A点,如果slow 走了n 步,则fast走了2n步。此时,如果fast不动,slow再走n步就会追上n步。再如果fast从head开始,则fast和slow还会在A点相遇。 很容易想到,他们之前肯定还会再遇到至少一次,这个点就是环入口。
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* findnode(ListNode* head, ListNode* slow){ ListNode* fast = head; while (fast!=slow){ fast = fast->next; slow = slow->next; } return fast; } ListNode *detectCycle(ListNode *head) { ListNode* fast = head; ListNode* slow = head; while (fast!=NULL and fast->next!=NULL){ fast = fast->next->next; slow = slow->next; if (fast==slow){ return findnode(head,slow); } } return NULL; }};
0 0
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 值得注意的7个 JavaScript 技巧
- View Animation
- Android学习03
- jQuery 表单验证控件 比较简单
- LVS入门2
- Linked List Cycle II
- 安卓游戏开发,vs win32到eclipse apk出现的跨平台问题
- nginx lvs 随笔
- 网络通信基础
- 点击textField没有响应与在屏幕上未看到创建的视图问题(UI)
- 关于C++中的多态
- UltraGrid过滤后的所有行
- 链表模板
- HAProxy MySQL负载均衡