Leetcode-141-判断链表有没有环

Leecode-141 Linked List Cycle

思路:快慢指针

题目描述:

判断链表有没有环

Solution:

  • 使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。

Java

Solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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) {
if(head == null){
return false;
}
ListNode l1 = head,l2 = head.next;
while(l1 != null & l2 !=null && l2.next != null){
if (l1 == l2) return true;
l1 = l1.next;
l2 = l2.next.next;
}
return false;
}
}

Python

Solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head: return False
l1 = head
l2 = head.next
while l1 and l2 and l2.next:
if l1 == l2:
return True
l1 = l1.next
l2 = l2.next.next
return False
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信