2.2.11—单链表—Linked List Cycle

来源:互联网 发布:java api中文版 编辑:程序博客网 时间:2024/06/05 08:30
描述
Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?


#include<iostream>using namespace std;const int n = 7;struct node{int data;node *next;};class mylist{node *head;public:mylist(){head = new node();head->next = NULL;}void CreateList(int a[], int n);void Display();friend bool IsCircle(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 == 3)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 IsCircle(mylist &list){bool flag = false;node *p = list.head->next;node *q = p->next->next;while (p&&q){if (p == q){flag = true;break;}else{p = p->next;q = q->next->next;}}return flag;}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[n] = { 1, 2, 3, 4,5,6,7 };mylist list;list.CreateList(a, n);//list.Display();//cout << endl;//===bool flag = IsCircle(list);if (flag)cout << "有环!" << endl;}


原创粉丝点击