链表反转 C++

ListNode* reverse1(ListNode* pHead)
{
	if(pHead == NULL)		
		return NULL;
	ListNode * p1 = NULL;
	ListNode * p2 = pHead;
	ListNode * p3 = pHead->next;
	while(p3!=NULL)
	{
		p2->next = p1;
		p1 = p2;
		p2 = p3;
		p3 = p3->next;
	}
	p2->next = p1;
	pHead = p2;
	return pHead;
}

完整类代码

<pre name="code" class="cpp">struct ListNode
{
	int data;
	ListNode * next;
};

class ReverseLink
{
public:
	ListNode * pHead;
	void init()
	{		
		pHead=NULL;
		for(int i=0; i<10; i++)
		{
			insert(i);
		}
	}
	//插入链表最后
	void insert(int data)
	{
		ListNode * p = new ListNode();
		p->data = data;
		p->next = NULL;

		if(pHead==NULL)
		{
			pHead = p;
			return;
		}
		
		ListNode * cur = pHead;
		while (cur->next!=NULL)
		{
			cur = cur->next;
		}		
		cur->next = p;
	}
	void print()
	{
		ListNode * p = pHead;
		while (p!=NULL)
		{
			cout<<p->data<<endl;
			p = p->next;
		}
	}
	//反转
	void reverse()
	{
		if(pHead->next == NULL)		
			return;		
		ListNode * p1 = NULL;
		ListNode * p2 = pHead;
		ListNode * p3 = pHead->next;
		while(p3!=NULL)
		{
			p2->next = p1;
			p1 = p2;
			p2 = p3;
			p3 = p3->next;
		}
		p2->next = p1;
		pHead = p2;
	}
};

int main()
{
    ReverseLink rl;
	rl.init();
	rl.print();
	cout<<"reverse"<<endl;
	rl.reverse();
	rl.print();
	return 0;
}





posted on 2016-03-20 18:37  长456风  阅读(185)  评论(0编辑  收藏  举报

导航