单链表的中间节点

#include<iostream>
using namespace std;

struct ListNode{
	int m;
	ListNode *next;
};

ListNode *Creat ()
{
	ListNode *pHead = nullptr;
	ListNode *p1,*p2;
	p1 = new ListNode;
	cout<<"Please Enter a Number:"<<endl;
	cin>>p1->m;
	while(p1->m != 0)
	{
		if(pHead == nullptr)
		{
			pHead = p1;
			p2 = p1;
		}
		else 
		{
			p2->next = p1;
			p2 = p1;
		}
		p1 = new ListNode;
		cout<<"Please Enter a Number:"<<endl;
		cin>>p1->m;
	}
	p2->next = nullptr;
	return pHead;
}

void print(ListNode *pHead)
{
	ListNode *p = pHead;
	while(p != nullptr)
	{
		cout<< p->m<< "\t";
		p = p->next;
	}
	cout<<endl;
}

ListNode *GetMiddleNode (ListNode *pHead)
{
	if(pHead==nullptr)
		return nullptr;
	if(pHead->next==nullptr)
		return pHead;
	ListNode *pAhead = pHead;
	ListNode *pBehind = pHead;
	/***偶数个结点时,输出后面的***/
	/*while(pAhead->next != nullptr)
	{
		pAhead = pAhead->next;
		pBehind = pBehind->next;
		if(pAhead->next != nullptr)
			pAhead = pAhead->next;
	}*/

	/***偶数个结点时,输出前面的***/
	while(pAhead->next!=nullptr&&pAhead->next->next!=nullptr)
	{
		pAhead = pAhead->next->next;
		pBehind = pBehind->next;
	}
	return pBehind;
}
int main ()
{
	ListNode *Head;
	Head = Creat();
	cout<<"The ListNode is"<<endl;
	print(Head);
	ListNode *Middle;
	Middle = GetMiddleNode(Head);
	cout<<"The Middle Node is:"<<Middle->m<<endl;


}

猜你喜欢

转载自blog.csdn.net/hannah_aimee/article/details/60878740