您的位置:首页 > 其它

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?

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: