鏈接:
141. 環(huán)形鏈表
題意:
求鏈表是否有環(huán)
解:
剛好昨天做完的初級(jí)算法鏈表題,翻轉(zhuǎn)和暴力
實(shí)際代碼:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-617455.html
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
bool hasCycle(ListNode *head)//翻轉(zhuǎn)法
{
if(head==nullptr) return false;
ListNode* newhead=nullptr,* oldhead=head;
for(;head!=nullptr;)
{
ListNode* temp=head->next;
head->next=newhead;
newhead=head;
head=temp;
}
if(oldhead==newhead&&newhead->next!=nullptr) return true;
return false;
}
/*
bool hasCycle(ListNode *head)//暴力法
{
if(head==nullptr) return false;
int n=0;
while(head->next!=nullptr)
{
head=head->next;
n++;
if(n>10007) return true;
}
return false;
}*/
int main()
{
}
限制:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-617455.html
- 鏈表中節(jié)點(diǎn)的數(shù)目范圍是
[0, 104]
-105 <= Node.val <= 105
-
pos
為-1
或者鏈表中的一個(gè) 有效索引 。
到了這里,關(guān)于2023-07-29力扣每日一題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!