LeetCode 题解(47): Linked List Cycle
来源:互联网 发布:got it 和get it的区别 编辑:程序博客网 时间:2024/06/06 02:43
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题解:
<pre name="code" class="cpp">/** * 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 || !head->next) return false; ListNode* one = head; ListNode* two = head; do { one = one->next; if(!two->next) return false; two = two->next->next; if(!two) return false; } while(one != two); return true; }};
同样的思想,更简单的写法
class Solution {public: bool hasCycle(ListNode *head) { ListNode* p, *q; p = q = head; while(q && q->next) { p = p->next; q = q->next->next; if(p == q) return true; } return false; }};
Java版
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public boolean hasCycle(ListNode head) { ListNode p, q; p = q = head; while(q != null && q.next != null) { p = p.next; q = q.next.next; if(p == q) return true; } return false; }}
Python版
class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): p = head q = head while q != None and q.next != None: p = p.next q = q.next.next if p == q: return True return False
0 0
- LeetCode 题解(47): Linked List Cycle
- LeetCode题解:Linked List Cycle
- [题解][LeetCode][Linked List Cycle]
- LeetCode题解:Linked List Cycle
- LeetCode题解:Linked List Cycle
- LeetCode Linked List Cycle & Linked List Cycle II题解
- LeetCode 题解(144): Linked List Cycle II
- [题解][LeetCode][Linked List Cycle II]
- LeetCode题解——Linked List Cycle
- LeetCode题解:Linked List Cycle II
- Leetcode题解 141. Linked List Cycle
- Leetcode题解 141. Linked List Cycle
- Leetcode题解 142. Linked List Cycle II
- LeetCode 141 Linked List Cycle题解
- leetcode题解-141. Linked List Cycle
- leetcode题解-142. Linked List Cycle II
- leetcode题解-141. Linked List Cycle
- leetcode题解-142. Linked List Cycle II
- Android与其他系统间DES加密解密的处理经验
- 二、LBP之多尺度LBP
- 三个轻量级WebServer--lighttpd,thttpd,shttpd介绍
- MFC:进程间通信
- HDU 3304 Interesting Yang Yui Triangle lucas定理
- LeetCode 题解(47): Linked List Cycle
- android shape的使用
- CSS阴影效果(兼容N多浏览器)
- RCP表格排序
- 去掉微信浏览器里的放大缩小按钮
- 顺序栈应用(十进制转换为2进制)
- 升序数组中寻找A[x] == x 的下标
- 八大渲染引擎的分析
- python时间操作