一个链表中包含环,请找出该链表的环的入口结点。
//#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;
//链表结构体
typedef struct ListNode
{
int val;
struct ListNode* next;
}ListNode;
//输入链表的数据
int read(void)
{
int a = 0;
cin >> a;
return a;
}
//创建链表
ListNode* create(int n) //n 链表长度
{
ListNode * head = NULL;
ListNode * p = NULL;
ListNode * q = NULL;
for (int i = 0; i<n; i++)
{
p = (ListNode*)malloc(sizeof(ListNode));
p->val = read();
p->next = NULL;
if (head == NULL)
head = p;
else
q->next = p;
q = p;
}
return head;
}
//将链表输出到终端
void readlist(ListNode* head)//遍历链表
{
ListNode* p = head;
do {
cout << p->val << " ";
p = p->next;
} while (p != NULL);
cout << endl;
}
void cycellist(ListNode* head, int k)//遍历链表
{
ListNode* p = head;
ListNode* pAhead = head;
for (int i = 0; i < k; ++i) {
//cout << pAhead->val << endl;
pAhead = pAhead->next;
}
while (p->next != NULL) {
p = p->next;
}
p->next = pAhead;
pAhead = head;
}
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if (pHead == NULL) return NULL;
ListNode *pfast = pHead->next, *pslow = pHead;
while (pfast != NULL&&pslow != NULL&&pfast != pslow) {
pslow = pslow->next;
pfast = pfast->next;
if (pfast != NULL)
pfast = pfast->next;
}
ListNode *ptemp = pfast->next;
int countNum = 1;
if (pfast == pslow&&pfast != NULL) {
while (ptemp != pfast) {
ptemp = ptemp->next;
++countNum;
}
}
else
return NULL;
ListNode *pNode1 = pHead, *pNode2 = pHead;
for (int i = 0; i<countNum; i++) {
pNode1 = pNode1->next;
}
while (pNode1 != pNode2) {
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
int main(int argc, char *argv[])
{
ListNode* my_list = NULL;
ListNode* r = NULL;
int n,m;//m个节点,n循环的节点数
cin >> n>>m;
my_list = create(m);//建立有m个节点的线性链表
//readlist(my_list);
cycellist(my_list, n); //建立有m个循环节点的链表
r=EntryNodeOfLoop(my_list);
cout << r->val << endl;
return 0;
}
ListNode* ReverseList(ListNode* pHead) {
if (pHead == NULL) return NULL;
stack<ListNode*>vec;
while (pHead) {
vec.push(pHead);
cout << pHead->val << endl;
pHead=pHead->next;
}
ListNode* phead = vec.top();
pHead = phead;
cout << vec.top()->val << endl;
vec.pop();
while (!vec.empty()) {
cout << (vec.top())->val << endl;
phead->next = vec.top();
phead = vec.top();
vec.pop();
}
phead->next = NULL;
return pHead;
}