从from到to的部分翻转,采用头插法。
//链表的部分翻转
#include<iostream>
#include <stdio.h>
using namespace std;
typedef struct tagSNode
{
int value;
tagSNode* pNext;
tagSNode(int v):value(v),pNext(NULL){}
}SNode;
void Reverse(SNode* ,int ,int );
void Destroy(SNode*);
void Print(SNode*);
int main()
{
SNode* pHead = new SNode(0);
int i;
//随机生成输入链表
for (i = 0; i<10; i++) {
SNode* p=new SNode(rand()%100); //rand()%100;表示将生成的随机数对100取余 即获得了范围0~99的一个随机数
p->pNext=pHead->pNext;
pHead->pNext = p;
}
Print(pHead);
Reverse(pHead,4,8);
Print(pHead);
Destroy(pHead);
return 0;
}
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;
}
}
void Print(SNode* p)
{
while (p->pNext) {
printf("%d->",p->value);
p=p->pNext;
}
printf("%d\n",p->value);
}