52-Linked List Cycle
来源:互联网 发布:邱一平麟龙软件破解版 编辑:程序博客网 时间:2024/04/30 08:21
- Linked List Cycle My Submissions QuestionEditorial Solution
Total Accepted: 102785 Total Submissions: 278248 Difficulty: Easy
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:快慢指针
一个走一步,一个走两步
最后如果相遇则有环(为什么呢?,考虑在环上的情况,因为快指针走的快,走的是2步,一定可以追上慢指针,那你可能会想走两步可能直接略过慢指针啊,假设某个时刻快指针在慢指针前一个位置,下一次便相遇,若果在前2个呢,那么下一次便和慢指针相邻,回到之前的情况,前1和前2涵盖了数位奇偶,所以总言之一定会相遇)
更多的是考虑到特殊情况,为空,只有一个节点,只有两个节点
/** * 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(head==NULL||head->next==NULL)return false; ListNode *p_quick=head,*p_slow=head; while(p_quick!=NULL&&p_quick->next!=NULL){ p_quick = p_quick->next->next; p_slow = p_slow->next; if(p_quick==p_slow)return true; } return false; }};
0 0
- 52-Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- C# 获取天气 JSON解析
- SDAU 课程练习3 1023
- UVA674Coin Change母函数模板题目
- LeetCode.283. Move Zeroes
- Java数据结构——中序表达式转后续表达式实现
- 52-Linked List Cycle
- 【最小生成树】CODE[VS] 2627 村村通
- bootstrap导航栏
- requests中文文档
- 关于UIView上添加一个手势,导致子视图为UIButton的无法响应
- 安卓开发——实现监听EditText的文字变化操作
- 最小加法表达式
- RecyclerCardView浅谈
- SpringMVC 单文件和多文件上传