步骤
1.遍历数组得到长度
2 生成长度为N的链表数组,遍历链表将节点放入数组内
3 针对链表数组进行快排partition
4将调整过的链表数组再维护成一个链表即可
#include"stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode*next;
ListNode(int x) :val(x), next(NULL) {}
};
void swap(vector<ListNode*>&arr, int l, int r)
{
int temp = arr[l]->val;
arr[l]->val = arr[r]->val;
arr[r]->val = temp;
}
void arrPartition(vector<ListNode*>&arr, int pivot)
{
int small = -1;
int big = arr.size();
int index = 0;
while (index < big)
{
if (arr[index]->val <pivot)
{
swap(arr, ++small, index++);
}
else if (arr[index]->val>pivot)
{
swap(arr, --big, index);
}
else
{
index++;
}
}
}
ListNode*listPartition(ListNode*head, int pivot)
{
if (head == NULL) return head;
ListNode*cur = head;
int i = 0;
while (cur != NULL)
{
cur = cur->next;
i++;
}
vector<ListNode*>res(i);
i = 0;
cur = head;
for (i = 0; i < res.size(); i++)
{
res[i] = cur;
cur = cur->next;
}
arrPartition(res, pivot);
for (int i = 1; i < res.size() ; i++)
{
res[i-1]->next = res[i];
}
res[i-1]->next = NULL;
return res[0];
}
int main()
{
ListNode*l1 = new ListNode(11);
l1->next = new ListNode(10);
l1->next->next = new ListNode(11);
l1->next->next->next = new ListNode(12);
l1->next->next->next ->next= new ListNode(7);
ListNode*l2 = new ListNode(9);
l2->next = new ListNode(10);
l2->next->next = new ListNode(11);
l2->next->next->next = new ListNode(12);
listPartition(l1, 11);
while (l1!= NULL)
{
cout << l1->val << endl;
l1 = l1->next;
}
}