leetCode:Linked List Cycle II
来源:互联网 发布:linux运维面试简历项目 编辑:程序博客网 时间:2024/06/05 22:29
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
设定两个指针,一个指针在前面,一个指针在后面。如果后面的指针一直小于前面的指针,那么就没有循环;
如果后面的指针超过前面的指针,那么就存在循环
#include<iostream>using namespace std;struct ListNode{ int val; ListNode * next; ListNode(int x):val(x),next(NULL){ };};class Solution{public: Solution(){ };//constructor; ListNode * detectCycle(ListNode *head){ ListNode * pre; ListNode * post; if(head==NULL || head->next==NULL) return NULL; pre=head;post=head->next; while(pre<post){ post=post->next; pre=pre->next; if(post==NULL) return NULL; }return post; }};int main(){ ListNode a=ListNode(-1); ListNode b=ListNode(-7); ListNode c=ListNode(7); ListNode d=ListNode(-4); ListNode e=ListNode(19); ListNode f=ListNode(6); ListNode g=ListNode(-9); ListNode h=ListNode(-5); ListNode i=ListNode(-2); a.next=&b;b.next=&c;c.next=&d;d.next=&e; e.next=&f;f.next=&g;g.next=&h;h.next=&i;i.next=&h; Solution sol; ListNode * temp=sol.detectCycle(&a); cout<<temp->val<<endl;// cout<<(temp==NULL)<<endl;}
0 0
- 【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
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- PCIe工作原理初探
- 答读者问(13):有关应届生求职面试资料和职业规划等问题
- Java之美[从菜鸟到高手演变]之设计模式
- printf中输出double的占位符、printf和scanf对于各种格式说明符可以接受的参数类型
- 使用Unity3D50个技巧-50 Tips for Working with Unity (Best Practices)
- leetCode:Linked List Cycle II
- Linux下IPC总结
- unity3d 怎样在一定时间连按两下键
- Android 更新UI的两种方法——handler和runOnUiThread()
- qsort函数(快速排序用法举例)
- cc2530的时钟
- duilib list控件扩展
- ARM体系架构--指令篇
- 最近点对问题