LEETCODE,[LeetCode]Link List Cycle

 2023-12-06 阅读 35 评论 0

摘要:Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? 思考:快慢指針,快指針一次走兩步,慢指針一次一步。若快指針跟慢指針指向同一個結點,則有環。若快指針到達鏈表末尾即指向NULL

Given a linked list, determine if it has a cycle in it.

Follow up: Can you solve it without using extra space?

思考:快慢指針,快指針一次走兩步,慢指針一次一步。若快指針跟慢指針指向同一個結點,則有環。若快指針到達鏈表末尾即指向NULL,說明沒有環。

/*** 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) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.if(!head||!head->next) return false;ListNode *p=head;ListNode *q=p->next;while(q&&q->next){if(p==q) return true;else{q=q->next->next;p=p->next;}}return false;}
};

  

LEETCODE、轉載于:https://www.cnblogs.com/Rosanna/p/3426533.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/192863.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息