您的位置:首页 > 编程语言 > C语言/C++

C++将链表划分为左边小,中间等,右边大于pivotKey的形式

2017-08-09 09:46 387 查看
#include <iostream>

struct Node {
int value;
Node *next;

Node(int data) : value(data), next(nullptr) {};

};

Node *ListPartition(Node * head, int pivot);

void swap(int arr[],int low, int high);

void partition(int arr[], int index, int length, int pivot);

int main()

{
Node n1(3);
Node n2(5);
Node n3(7);
Node n4(2);
Node n5(4);
Node n6(1);
Node n7(0);

n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = nullptr;

Node * cur = ListPartition(&n1, 3);
while (cur != nullptr)
{
std::cout << cur->value << std::endl;
cur = cur->next;
}

system("pause");
return 0;

}

Node *ListPartition(Node * head, int pivot)

{
if (head == nullptr || head->next == nullptr)
{
return head;
}

int length = 0;
Node *cur = head;
while (cur != nullptr)
{
++length;
cur = cur->next;
}

cur = head;

int *pArr = (int *)malloc(length);

for (int i = 0; i < length; ++i)
{
pArr[i] = cur->value;
cur = cur->next;
}

cur = head;
partition(pArr, 0, length, pivot);
for (int i = 0; i < length; ++i)
{
cur->value = pArr[i];
cur = cur->next;
}
//free(pArr);
return head;

}

void swap(int arr[], int low, int high)

{
int tmp = arr[low];
arr[low] = arr[high];
arr[high] = tmp;

}

void partition(int arr[], int index, int length, int pivot)

{
int Lp = -1;
int Hp = length - 1;
while (index < Hp)
{
if (index < Hp && arr[index] < pivot)
{
swap(arr, ++Lp, index++);
}
if (index < Hp && arr[index] == pivot)
++index;
else if (index < Hp && arr[index] > pivot)
swap(arr, Hp--, index);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表划分
相关文章推荐