Leetcode_141_Linked List Cycle
来源:互联网 发布:江西网络问政 编辑:程序博客网 时间:2024/05/02 00:19
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42833739
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
(1)题意为判断一个链表是否带环。这道题在校招笔试和面试中出现的次数还是比较多的。
(2)要判断是否带环,只需设置两个指针,从链表的起始点开始,分别往后遍历链表中的节点,如果在遍历的过程中两指针相遇,说明链表带有环。但是为了让它们在链表带环的情况下能够相遇,需要对两指针设置不同的步调,一个指针每次前进一步,另一个指针一次前进两步,这样如果前一个指针遍历到最后一个节点为空,则说明链表不带环;否则在遍历的过程中如果第一个指针和第二个指针相遇,则说明链表带环。
(3)希望本文对你有所帮助。
算法代码实现如下:
/** * @author liqq */public boolean hasCycle(ListNode head) {if (head == null || head.next == null)return false;ListNode curr = head;ListNode sec = head;while (sec.next != null && sec.next.next != null) {curr = curr.next;sec = sec.next.next;if (curr == sec) {return true;}}return false;}
1 0
- Leetcode_141_Linked List Cycle
- leetcode_141_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
- dede更新出现:读取频道信息失败,无法进行后续操作
- CentOS 7 巨大变动之 firewalld 取代 iptables
- UOJ Round5总结
- java服务器端调用JPush极光推送api推送通知消息
- 迁移学习(Transfer Learning)
- Leetcode_141_Linked List Cycle
- 异或运算进行整数交换的陷阱
- uva 512 追踪电子表格中的单元格
- Tautology POJ 3295
- uva679Dropping Balls 入门经典II 第六章数据结构基础 例题6-6
- Parencodings
- curl 和 Wget 的比较
- hdu 1864 最大报销额 DP
- uBOOT 错误1