<leetcode系列> Linked List Cycle
来源:互联网 发布:数据决策分析系统 编辑:程序博客网 时间:2024/06/05 01:19
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?
题目意思: 给定一个链表, 判断里面是否含有环.
原题链接: https://leetcode.com/problems/linked-list-cycle/
这是一个典型的运用快指针和慢指针的题目.快慢指针是指移动步长不一样,快指针每次移动的步长要大一些,慢指针每次移动的步长要小一些.
如果链表没有环,则最后必然会有尾节点,就如同两个人在操场跑步, 快指针会第一个冲过终点(NULL).
如果链表有环,则跑的快的人,必然会在某个时候再次遇到跑的慢的人,这个时候跑的快的人正好在环里超过跑得慢的那个人1圈或n圈.
代码如下:
bool hasCycle(struct ListNode *head) { if ((NULL == head) || (NULL == head->next)) { return false; } int slowStep = 1; int fastStep = 2; struct ListNode* slow = head; struct ListNode* fast = head; while (true) { for (int j = 0; j < fastStep; ++j) { fast = fast->next; if (NULL == fast) { return false; } if (fast == slow) { return true; } } for (int i = 0; i < slowStep; ++i) { slow = slow->next; } }}
0 0
- <leetcode系列> Linked List Cycle
- 【Leetcode长征系列】Linked List Cycle
- 【Leetcode长征系列】Linked List Cycle II
- <leetcode系列> Linked List Cycle II
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 阅读android程序从AndroidManifest.xml开始
- Oracle启动监听遇到的问题
- linux驱动结构
- 将特殊字符插入数据库
- JVM学习笔记系列
- <leetcode系列> Linked List Cycle
- 图像分割之(二)Graph Cut(图割)
- [转载]java servlet过滤器控制frame框架中的页面跳转
- 微信分享SDK开发
- hihocoder 1103 Colorful Lecture Note(字符串处理)
- C语言中的值传递和引用传递(地址传递)
- POJ1644 放苹果
- 为Python添加默认模块搜索路径
- 【线性代数公开课MIT Linear Algebra】 第五课 排列矩阵、转置、向量空间与列空间