单链表环相关问题

来源:互联网 发布:2017淘宝违规考试答案 编辑:程序博客网 时间:2024/06/10 01:09
// ConsoleApplication6.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>  #include <string>  #define LEN 8using namespace std;#include <stdio.h>struct Node{int val;Node *next;};//判断是否有环bool isLoop(Node *pHead){Node * fast = pHead;Node * slow = pHead;//如果无环,则fast先走到终点//当链表长度为奇数时,fast->Next为空//当链表长度为偶数时,fast为空while (fast != NULL && fast->next != NULL){fast = fast->next->next;slow = slow->next;//如果有环,则fast会超过slow一圈if (fast == slow){break;}}if (fast == NULL || fast->next == NULL)return false;elsereturn true;}//计算环的长度int loopLength(Node * pHead){if (isLoop(pHead) == false)return 0;Node * fast = pHead;Node * slow = pHead;int length = 0;bool begin = false;bool agian = false;while (fast != NULL && fast->next != NULL){fast = fast->next->next;slow = slow->next;//超两圈后停止计数,挑出循环if (fast == slow && agian == true)break;//超一圈后开始计数if (fast == slow && agian == false){begin = true;agian = true;}//计数if (begin == true)++length;}return length;}//求出环的入口点Node* findLoopEntrance(Node * pHead){Node * fast = pHead;Node * slow = pHead;while (fast != NULL && fast->next != NULL){fast = fast->next->next;slow = slow->next;//如果有环,则fast会超过slow一圈if (fast == slow){break;}}if (fast == NULL || fast->next == NULL)return NULL;slow = pHead;while (slow != fast){slow = slow->next;fast = fast->next;}return slow;}//单循环链表创建  Node *CreateListCircle(Node *head1){Node *p, *q,*head,*tail;p = head1; int i = 0; int n = 10;head = tail = NULL;for (i = 1; i < n; i++){p = new Node();p->val = i;if (head == NULL){head = p;q = p;}else{q->next = p;//尾插法q = p;}}p->next = head;tail = p;return tail;}int main(){Node *head;head = new Node();Node* p;p= CreateListCircle(head);if( isLoop(p)) cout<<"有环";else cout << "wuhuan";cout<<findLoopEntrance(p)->val;cout << loopLength(p);}

原创粉丝点击