链表的部分翻转

#include <iostream>
#include <vector>
#include <string>

using namespace std;

typedef struct tagSNode
{
	int value;
	tagSNode* pNext;

	tagSNode(int x) :value(x), pNext(NULL){};
}SNode;
void Print(SNode* p)
{
	while (p!=NULL)
	{
		if (p->pNext == NULL)
		{
			printf("%d", p->value);
			
		}
		else
		{	
			printf("%d->", p->value);
			
		}
		p = p->pNext;
		
	}
	printf("\n");
}

SNode* Tranverse(SNode* pHead,int m,int n)
{
	SNode* pLink = pHead;
	int i;
	for (i=0; i < m-1; i++)
	{
		pLink= pLink->pNext;
	}

	SNode* pPre = pLink->pNext;
	SNode* pCur = pPre;
	SNode* pNext;//关键在于pNext暂时存放后面的部分,不至于被翻转搅乱。而且翻转过程用到了四个节点指针。

	
	for (i=0; i < n-m+1; i++)
	{
		pNext = pCur->pNext;
		pCur->pNext = pLink->pNext;
		pLink->pNext = pCur;
		pPre->pNext = pNext;
		pCur = pNext;

	}
	return pHead;


}
int main()
{
	SNode* pHead1 = new SNode(0);
	int i;
	for (i = 10; i >0; i--)
	{
		SNode* p = new SNode(i);
		p->pNext = pHead1->pNext;
		pHead1->pNext = p;
	
	}
	Print(pHead1);

	Tranverse(pHead1,4,8);

	Print(pHead1);
	

	
}

posted @ 2016-03-13 21:17  牧羊少年10号  阅读(118)  评论(0编辑  收藏  举报