LeetCode 题解(144): Linked List Cycle II
来源:互联网 发布:淘宝卖家在哪找货源 编辑:程序博客网 时间:2024/06/07 10:19
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
题解:
双指针fast进二,slow进一。当fast == slow时有环。
C++版:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { if(!head || head->next == NULL) return NULL; ListNode* fast = head, *slow = head; while(fast && fast->next) { fast = fast->next->next; slow = slow->next; if(fast == slow) break; } if(fast == slow && fast) { ListNode* p = head; while(p != fast) { p = p->next; fast = fast->next; } return fast; } return NULL; }};
Java版:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null) return null; ListNode fast = head, slow = head; while(fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if(fast == slow) break; } if(fast == slow) { ListNode p = head; while(p != fast) { p = p.next; fast = fast.next; } return p; } return null; }}
Python版:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): if head == None or head.next == None: return None fast, slow = head, head while fast != None and fast.next != None: fast = fast.next.next slow = slow.next if fast == slow: break if fast == slow: p = head while p != fast: p = p.next fast = fast.next return p return None
0 0
- LeetCode 题解(144): Linked List Cycle II
- LeetCode Linked List Cycle & Linked List Cycle II题解
- [题解][LeetCode][Linked List Cycle II]
- LeetCode题解:Linked List Cycle II
- Leetcode题解 142. Linked List Cycle II
- leetcode题解-142. Linked List Cycle II
- leetcode题解-142. Linked List Cycle II
- LeetCode 题解(47): Linked List Cycle
- LeetCode题解——Linked List Cycle II
- LeetCode题解:Linked List Cycle
- [题解][LeetCode][Linked List Cycle]
- LeetCode题解:Linked List Cycle
- LeetCode题解:Linked List Cycle
- (leetcode)Linked List Cycle II
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Spring MVC3.0.5搭建全程 .
- 软件定时器osTimerCreate返回NULL
- 九度1192回文字符串
- 学习日记-MIT[计算机科学与编程导论]-5
- 小白学开发(iOS)基础C_static和extern对变量的作用(2015-07-20)
- LeetCode 题解(144): Linked List Cycle II
- Hive:向内部表和外部表加载数据
- CentOS6 图形界面'Basic server'条件下的(gnome)安装
- linux管道的那点事
- pinyin4j+jxl + jdbc 批处理
- 二叉树的遍历
- Android实现图标右上角红色小圆球提示气泡
- 小白学开发(iOS)基础C_关键字_typedef(2015-07-20)
- IOS 创建目录/文件夹