循环链表入口(调试)

一个链表中包含环,请找出该链表的环的入口结点。

//#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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值