链表的部分翻转

给定一个链表,翻转该链表从m到n的位置。要求直接翻转而非申请新空间。

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <cstdio>

using namespace std;

typedef struct tagSNode
{
	int  value;
	tagSNode* pNext;

	tagSNode(int v) :value(v), pNext(NULL){}
}SNode;

void Reverse(SNode* pHead, int from, int to)
{
	SNode* pCur = pHead->pNext;
	int i;
	for (i = 0; i<from - 1; i++)
	{
		pHead = pCur;
		pCur = pCur->pNext;
	}

	SNode* pPre = pCur;
	pCur = pCur->pNext;
	to--;
	SNode* pNext;
	for (; i<to; i++)
	{
		//此处需要结合图示
		pNext = pCur->pNext;
		pCur->pNext = pHead->pNext;
		pHead->pNext = pCur;
		pPre->pNext = pNext;
		pCur = pNext;
	}
}

void Destroy(SNode* p)
{
	SNode* next;
	while (p)
	{
		next = p->pNext;
		delete p;
		p = next;
	}
}

int main()
{
	SNode* pHead = new SNode(0);
	int i;
	for (i = 0; i<10; i++)
	{
		SNode* p = new SNode(rand() % 100);
		p->pNext = pHead->pNext;
		pHead->pNext = p;
	}
	//Print(pHead);
	Reverse(pHead, 4, 8);
	//Print(pHead);
	//Print(pHead);
	Destroy(pHead);

	return 0;
}


            
posted @ 2016-03-02 20:35  牧羊少年10号  阅读(136)  评论(0编辑  收藏  举报