141. Linked List Cycle
来源:互联网 发布:淘宝人工客服在哪里 编辑:程序博客网 时间:2024/06/05 16:19
题目:Linked List Cycle
原题链接:https://leetcode.com/problems/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?
给出一个单链表,判断是不是有环。
尽量不要占用额外的空间。
设两个指针p1,p2,其中p1指针每次扫描前进一格,p2指针每次扫描前进两格。如果当前链表没有环的话,p2肯定会先扫描到链表的结尾,如果有环的话,p1和p2最终都会进入环中,由于两者的速度不一样,那么经过若干次的循环,p1和p2一定会重新碰到。
代码如下:
/** * 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* p1 = head, *p2 = head->next->next; while(p2 && p2->next) { if(p2 == p1) return true; p1 = p1->next; p2 = p2->next->next; } return false; }};
0 0
- 141.Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141.Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- 141. Linked List Cycle
- myeclipse提示内存不足解决 (转)
- 在linux系统下,创建oracle数据库表空间、用户权限操作功能
- 一次网络请求的流程
- Android中MVP模式与MVC模式比较(含示例)
- HDU 2680 Choose the best route 最短路
- 141. Linked List Cycle
- WEB前端模块化基础知识
- uC/OS-II任务就绪表及任务调度
- Non-terminating decimal expansion问题重新温习BigDecimal roundMode
- [已解决]junit.framework.AssertionFailedError: No tests found in com.wbm.app.business.NeedLoginTestCase
- Hadoop伪分布式环境搭建(二)
- Java 类与对象
- J-Link烧写STM32失败的问题
- Handler、Thread和HandlerThread的差别