3.给定一个链表,两个整数m,n,m<n,翻转链表中m到n的元素
#include <iostream>
using namespace std;
typedef struct tagSNode{
int value;
tagSNode* pNext;
tagSNode(int v) : value(v), pNext(NULL){}
}SNode;
void Print(SNode *p){
SNode *q = p;
while (q != NULL){
cout << q->value<<" ";
q = q->pNext;
}
cout << endl;
}
void Destory(SNode *p){
SNode *next;
while (p){
next = p->pNext;
delete p;
p = next;
}
}
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;
}
}
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);
Destory(pHead);
return 0;
}
4、给定一个链表和一个值x,将链表划分成两部分,使得划分后小于x的结点在前,大于等于x的结点在后,并保持原链表中的顺序
void Partition(SNode *pHead, int pivotKey){
SNode *pLeftHead = new SNode(0);
SNode *pRightHead = new SNode(0);
//两个链表的当前最后一个元素
SNode *left = pLeftHead;
SNode *right = pRightHead;
SNode *p = pHead->pNext;
while (p){
if (p->value < pivotKey){
left->pNext = p;
left = p;
}
else{
right->pNext = p;
right = p;
}
p = p->pNext;
}
left->pNext = pRightHead->pNext;
right->pNext = NULL;
pHead->pNext = pLeftHead->pNext;
delete pLeftHead;
delete pRightHead;
}