leetCode 141. Linked List Cycle 链表

简介:

141. 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?

题目大意:

判断一个单链表是否存在环。

思路:

采用快慢指针来处理。

代码如下:


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
26
27
28
29
30
31
/**
  * 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) {
         ListNode *slow,*fast;
         if (NULL == head || NULL == head->next)
             return  false ;
         slow = head;
         fast = head;
         fast = fast->next->next;
         slow = slow->next;
         while (1)
         {
             if (fast == NULL || fast->next == NULL)
                 return  false ;
             if (fast == slow || fast->next == slow)
                 return  true ;
             slow = slow->next;
             fast = fast->next->next;
         }
         return  false ;
         
     }
};


总结:快慢指针

快慢指针中的快慢指的是移动的步长,即每次向前移动速度的快慢。例如可以让快指针每次沿链表向前移动2,慢指针每次向前移动1次。

快慢指针可以用来求一个单链表是否存在环,还可以用来求一个单链表的中间位置。



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837479

相关文章
|
1天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
1天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
13 4
|
1天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
10 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
1天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
1天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
1天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
1天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
1天前
|
C语言 C++ 索引
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表