今天,我又來了啊,繼續刷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% 的用戶
這效果,太垃圾了。