2.2.12—单链表—Linked List Cycle II
2017-08-04 11:01
309 查看
描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
#include<iostream> using namespace std; const int n = 8; struct node { int data; node *next; }; node *firstnode = NULL; class mylist { node *head; public: mylist() { head = new node(); head->next = NULL; } void CreateList(int a[], int n); void Display(); friend bool FirstNode(mylist &list); ~mylist(); }; void mylist::CreateList(int a[], int n) { node *p = head; node *temp = head; for (int i = 0; i < n; i++) { node *q = new node(); q->data = a[i]; p->next = q; p = q; if (i == 2) temp = p; } //p->next = NULL; p->next = temp;//产生环 } void mylist::Display() { node *p = head->next; while (p) { cout << p->data << " "; p = p->next; } cout << endl; } bool FirstNode(mylist &list) { //判断是否有环 bool flag = false; node *p = list.head->next; node *q = list.head->next; while (p&&q) { //=== p = p->next; if (q->next) q = q->next->next; else { flag = false; break; } //=== if (p == q) { flag = true; break; } } //无环 if (!flag) return false; //有环 node *slow1 = list.head->next; node *slow2 = p; while (slow1 != slow2) { slow1 = slow1->next; slow2 = slow2->next; } firstnode = slow1; return true; } mylist::~mylist()//含有环的链表如何释放 { node *p = head; for (int i = 0; i < n + 1; i++) { node *temp = p->next; delete p; p = temp; } } int main() { //=== int a = { 1, 2, 3, 4, 5, 6, 7,8 }; mylist list; list.CreateList(a, n); //list.Display(); //cout << endl; //=== bool flag = FirstNode(list); if (flag) cout << firstnode->data << endl; }
相关文章推荐
- Linked List Cycle II 求单链表环的入口
- LeetCode Linked List Cycle II 单链表环2 (找循环起点)
- 求单链表环的入口结点 Linked List Cycle II
- 2.2.12 Linked List Cycle II
- leetcode - Linked List Cycle II
- [Leetcode] #141#142 Linked List Cycle I & II
- LeetCode | Linked List Cycle II
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- Leetcode#142(链表)-Linked List Cycle II
- LeetCode刷题(C++)——Linked List Cycle II(Medium)
- LeetCode "Linked List Cycle II"
- [leetcode]142 Linked List Cycle II
- Linked List Cycle II -- leetcode
- Linked List Cycle II
- [LeetCode]Linked List Cycle II
- Java for LeetCode 142 Linked List Cycle II
- LeetCode-Linked List Cycle II
- leetcode之Linked List Cycle II
- LeedCode:Linked List Cycle II
- LeetCode 之 Linked List Cycle I II — C++ 实现