LeetCode:142. Linked List Cycle II
来源:互联网 发布:2016fc2破解版域名设置 编辑:程序博客网 时间:2024/05/03 12:57
题目链接:
Linked List Cycle II
题目描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
题目解释:
题目的要求比较简单,给定一个链表,如果这个链表是循环的,找出这个链表循环开始的地方,如果这个链表并没有循环,则返回NULL。
当然题目还要求空间复杂度为O(1).
解题方案:
- 利用快慢指针,判断该链表是否为循环链表,并找出循环中的一个节点。
- 如果为循环指针,从链表头部开始判断当前节点是否在循环区域。
- 判断当前节点是否在循环区域的方式为:利用步骤1找到的节点fast,迭代求fast节点的下一节点,如果该节点在循环内,那么该节点肯定会与fast相遇,若不在循环中,fast节点会与步骤1中的慢指针相遇。
AC代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode *detectCycle(struct ListNode *head) { if(head == NULL) return NULL; struct ListNode *fast = head; struct ListNode *slow = fast; bool isCycle = false; while(true){ fast = fast->next; if(!fast) break; fast = fast->next; if(!fast) break; slow = slow->next; if(fast == slow){ isCycle = true; break; } } printf("%d %d\n", slow->val, isCycle); if(isCycle){ struct ListNode *f = head; while(f){ if(f == fast) return f; while(true){ fast = fast->next; if(f == fast) return f; if(slow == fast) break; } f = f->next; } } else return NULL;}
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- 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 @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- 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
- iOS冰与火之歌番外篇 - 在非越狱手机上进行App Hook
- 在Windows使用VC编译ICU
- How to check and uncheck a checkbox with jQuery
- 算法的封装与切换——策略模式
- Material Design
- LeetCode:142. Linked List Cycle II
- KCP同 UDT/ENET的性能比较
- 导入数据时发生数据插入异常:executeSQL异常。
- Q_PROPERTY 的属性名称 必须是确定的,如果需要多态,属性名称写基类的
- 行为型模式11之2-TemplateMethod模板方法模式例子理解
- Imageswitcher.setFactory
- Mybatis generator 添加记录时返回自增主键
- 非常全的linux面试笔试题及参考答案
- 嫌写后端代码单调又繁重?Bomb SDK为你打包移动后端开发工作