#include "List.h"
#include <vector>
using namespace std;
/*时间复杂度N,空间复杂度N,且不考虑内部顺序的解法(即不稳定的解法)*/
void arrPartition(Node* arrNode[], int pivot, int n);
void swap(Node* arrNode[], int i, int j);
Node* ListPart(Node* head, int pivot)
{
if(head == nullptr)
return head;
Node* cur = head;
int n = 0;
while(cur)
{
++n;
cur = cur->next;
}
Node* nodArr[n];
cur = head;
for(int i = 0; i != n; ++i)
{
nodArr[i] = cur;
cur = cur->next;
}
arrPartition(nodArr, pivot, n);
for(int i = 1; i != n; ++i)
nodArr[i - 1]->next = nodArr[i];
nodArr[n - 1]->next = nullptr;
return nodArr[0];
}
void arrPartition(Node* arrNode[], int pivot, int n)
{
int small = -1;
int big = n;
int index = 0;
while(index != big)
{
if(arrNode[index]->value < pivot)
swap(arrNode, ++small, index++);
else if(arrNode[index]->value > pivot)
swap(arrNode, --big, index++);
else
++index;
}
}
void swap(Node* arrNode[], int i, int j)
{
Node* tmp = arrNode[i];
arrNode[i] = arrNode[j];
arrNode[j] = tmp;
}
/*时间复杂度N,空间复杂度1,且考虑内部顺序的解法(即稳定的解法)*/
Node* ListPart2(Node* head, int pivot)
{
Node* sH = nullptr;//small start
Node* sT = nullptr; //small end;
Node* eH = nullptr; //equal start
Node* eT = nullptr; //equal end
Node* bH = nullptr; //big start
Node* bT = nullptr; //big end
Node* next = nullptr;
while(head)
{
next = head->next;
head->next = nullptr;
if(head->value < pivot)
{
if(sH)
{
sT->next = head;
sT = head;
}
else
{
sH = head;
sT = head;
}
}
else if(head->value == pivot){
if(eH)
{
eT->next = head;
eT = head;
}
else
{
eH = head;
eT = head;
}
} else {
if(bH)
{
bT->next = head;
bT = head;
}
else
{
bH = head;
bT = head;
}
}
head = next;
}
if(sT)
{
sT->next = eH;
eT = eT == nullptr? sT:eT;
}
if(eT)
eT->next = bH;
return sH != nullptr? sH : eH != nullptr ? eH :bH;
}
int main()
{
Node* pNode0 = new Node(0);
Node* pNode1 = new Node(1, pNode0);
Node* pNode2 = new Node(2, pNode1);
Node* pNode3 = new Node(2, pNode2);
Node* pNode4 = new Node(1, pNode3);
Node* pNode5 = new Node(0, pNode4);
pNode5 = ListPart2(pNode5, 0);
Print(pNode5);
cout << "=====================" << endl;
pNode5 = ListPart(pNode5, 2);
Print(pNode5);
}
将单向链表按某值划分成左边小、中间相等、右边大的形式
猜你喜欢
转载自blog.csdn.net/wzc2608/article/details/80674420
今日推荐
周排行