题目
分析给定一个链表和一个值X,将链表划分成两部分,使得划分后小于X的结点在前,大于等于X的结点在后。在这两部分中要保持原链表中的出现顺序。
如:给定链表1->4->3->2->5->2和X=3,返回1->2->2->4->3->5。
代码如下分别申请两个指针p1和p2,小于x的添加到p1种,大于等于x的添加到p2中,最后,将p2连接到p1的末端即可。
时间复杂度是O(N),空间复杂度是O(1);该问题其实说明:快速排序对于单链表存储结构仍然使用
注:不是所有排序都方便使用链表存储,如堆排序,将不断的查找数组的n/2和n的位置,用链表做存储结构会不太方便。
// suanfa1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
typedef struct tagSNode
{
int value;
tagSNode* pNext;
tagSNode(int v): value(v), pNext(NULL){}
}SNode;
void Print(SNode* pHead)
{
if (!pHead)
{
return;
}
SNode* p = pHead->pNext;
while(p)
{
printf("%d ", p->value);
p = p->pNext;
}
printf("\n");
}
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;
}
void Destory(SNode* pHead)
{
SNode* next;
while (pHead)
{
next = pHead->pNext;
delete pHead;
pHead = next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SNode* pHead = new SNode(0);
pHead->pNext = NULL;
for (int i = 0; i < 10; i++)
{
SNode* p = new SNode(rand() % 100);
p->pNext = pHead->pNext;
pHead->pNext = p;
}
Print(pHead);
Partition(pHead, 40);
Print(pHead);
Destory(pHead);
system("pause");
return 0;
}