141、142 Linked List Cycle & II
来源:互联网 发布:淘宝返利机器人骗局 编辑:程序博客网 时间:2024/06/03 17:55
141、 Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
非常简单的一道题,如果链表有环,则在遍历的时候永远不会结束,一直在环内转圈。
所以,设置快慢指针,如果相遇,则说明有环。
代码(C++)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { if (NULL == head || NULL == head->next) return false; ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }};
142、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.
思路
在上一题的基础上,slow和fast相遇后,slow和head同时出发,每次一个步长,相遇的时候就是交点。
代码(C++)
/** * 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 false; ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { ListNode* tmp = head; while (tmp != slow) { tmp = tmp->next; slow = slow->next; } return tmp; } } return NULL; }};
0 0
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- 141、142 Linked List Cycle & II
- 142Linked List Cycle II
- 142Linked List Cycle II
- Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II
- LeetCode 141 Linked List Cycle和142 Linked List Cycle II
- Leetcode 141/142 (链表题) Linked List Cycle && 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
- java中RowSet用法
- POJ2478 Farey Sequence
- 计数排序
- Android单个app的aidl跨进程调用
- Spring 事务机制详解
- 141、142 Linked List Cycle & II
- Python中元组,列表,字典的区别
- 实现一个栈,要求push,pop,Min的操作时间复杂度为O(1)
- Java多线程 -- JUC包源码分析18 -- ConcurrentSkipListMap(Set)/TreeMap(Set)/无锁链表
- 寻找第K大的数的方法总结
- uC/OS – II中的任务_读书笔记_3
- JS实现图片轮播效果
- Tomcat(JVM)监控方法
- 单链表排序