今天,我又来了啊,继续刷leetcode,上瘾不上火,哈哈哈。
题目:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos
是 -1
,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1 输出:false 解释:链表中没有环。
那么,这个题怎么做呢?我想的是用对每个结点的data域进行赋值,若后面的某个点的值小于当前flag,那么必然就是有环的,而想象很美好,但是还是有问题。很不完善,有的情况可以解决,有的不行。错误代码如下,不要用这个啊!!!提交通过不过的:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
int flag=0;
struct ListNode *p1=head;
if(p1==NULL||p1->next==NULL){
flag=-1;
}
else{
while(p1){
p1->val=flag;
flag++;
if(p1->next==NULL){
flag=-1;
break;
}
else if (p1->next->val<flag){
flag=p1->next->val;
break;
}
p1=p1->next;
}
}
if(-1==flag)
return false;
else
return true;
}
继续改进:双指针,强的一批
迟早追得上,若有环,哈哈哈
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
int flag=0;
if(head==NULL||head->next==NULL){
flag=-1;
}
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast != NULL && fast->next !=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
int flag=0;
if(head==NULL||head->next==NULL){
flag=-1;
}
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast != NULL && fast->next !=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
结果;
执行用时 : 20 ms, 在Linked List Cycle的C提交中击败了41.51% 的用户
内存消耗 : 8.4 MB, 在Linked List Cycle的C提交中击败了0.00% 的用户
这效果,太垃圾了。