Leetcode: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  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(head==NULL) return false;
13         ListNode* Node = NULL;
14         ListNode* temp = NULL;
15         Node = head;
16         while(head->next!=NULL)
17         {
18             temp = head;
19             head = head->next;
20             temp->next = Node;
21             if(head->next==Node)
22                 return true;
23         }
24         return false;
25     }
26 };

方案二:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         // head ==null?
13         if(head==NULL) return false;
14         ListNode *fast = head->next, *slow=head;
15         while(fast!=NULL && fast->next!=NULL)
16         {
17             if(fast==slow)
18                 return true;
19             fast = fast->next->next;
20             slow = slow->next;
21         }
22         return false;
23     }
24 };

建议与易出错地方:

1.在纸上写代码时,开始留些空白,如果需要处理边界情况,可直接加上。

2. 声明指针变量时一定要保持*在变量上的好习惯,否则容易写成 ListNode* fast=head, slow = head; 这就错了!

3. 过程中一个错是  开始初始化直接

 ListNode *fast = head, *slow=head;
后面fast==slow的判断,就直接为真了。

转载于:https://www.cnblogs.com/soyscut/p/3691521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值