链表的部分反转
题目要求:
给定一个链表,翻转该链表从m到n的位置。
要求直接翻转而非申请新空间
如:给定1→5→7→4→6→3→8→5,m=2,n=4,返回
1→4→7→5→6→3→8→5
假定给出的参数满足:1≤m≤n≤链表长度。
算法核心思想
pNext = pCur->pNext;
pCur->pNext = pHead->pNext;
pHead->pNext = pCur;
pre->pNext = pNext;
pCur = pNext;
代码段
代码块语法遵循标准C/C++代码
/*
* 问题描述:链表的部分反转
* C/C++ 语言
*
* @author Erice_s
* binbin_Erices@163.com
* @date 2017/11/9
*
*/
#include<iostream>
#include<time.h>
using namespace std;
typedef struct tagSNode
{
int value;
tagSNode *pNext;
tagSNode(int v) :value(v), pNext(NULL){}
}SNode;
void Print(SNode*p)
{
if (p == NULL)
{
cout << "Print failure:(p==NULL)\n";
return;
}
p = p->pNext;
while (p)
{
cout << p->value << " ";
p = p->pNext;
}
}
void Destroy(SNode*p)
{
SNode *next;
while (p)
{
next = p->pNext;
delete p;
p = next;
}
}
int *Reserve(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 *pre = pCur;
pCur = pCur->pNext;
to--;
SNode *pNext;
for (; i < to; i++)
{
pNext = pCur->pNext;
pCur->pNext = pHead->pNext;
pHead->pNext = pCur;
pre->pNext = pNext;
pCur = pNext;
}
return 0;
}
int main(void)
{
SNode *pHead = new SNode(0);
int i;
time_t ts;
srand((unsigned int)time(&ts));
for (i = 0; i < 10; i++)
{
SNode *p = new SNode(rand() % 10);
p->pNext = pHead->pNext;
pHead->pNext = p;
}
Print(pHead);
Reserve(pHead, 3, 6);
cout << endl;
Print(pHead);
Destroy(pHead);
system("pause");
return 0;
}