首页 > 代码库 > 141.Linked List Cycle
141.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?
HideTags
Linked List Two Pointers
#pragma once #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; bool hasCycle(ListNode *head) { ListNode* p1 = head; ListNode* p2 = head; while (p1&&p2) { p1 = p1->next; p2 = p2->next; if (p2) p2 = p2->next; else return false;//到头,一定无环 if (p1 == p2) return true; } return false; } void main() { ListNode* l1 = new ListNode(1); ListNode* l2 = new ListNode(2); ListNode* l3 = new ListNode(3); ListNode* l4 = new ListNode(4); ListNode* l5 = new ListNode(4); l1->next = l2; l2->next = l3; //l3->next = l1; l4->next = l1; cout << hasCycle(l1) << endl; /*cout << hasCycle(l2) << endl; cout << hasCycle(l3) << endl; cout << hasCycle(l4) << endl; cout << hasCycle(l5) << endl; cout << hasCycle(l5->next) << endl;*/ system("pause"); }
141.Linked List Cycle
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。