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

C++链表划分左边小中间等右边大 时间复杂度O(n) 空间复杂度O(1)

2017-08-09 11:52 459 查看
#include <iostream>

struct Node {
int value;
Node *next;

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

};

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

void Print(Node *head);

int main()

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

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

std::cout << "Before Partition:  " << std::endl;
Print(&n1);
std::cout << "After Partition: " << std::endl;
Print(List_Partition_Pro(&n1, 4));

system("pause");
return 0;

}

Node * List_Partition_Pro(Node *head, int pivot)

{
Node * SH = nullptr, * ST = nullptr;
Node * MH = nullptr, * MT = nullptr;
Node * BH = nullptr, * BT = nullptr;
Node * next = nullptr;

while (head != nullptr){
next = head->next;
head->next = nullptr;

if (head->value < pivot) {
if (SH == nullptr) {
SH = head;
ST = head;
}else{
ST->next = head;
ST = head;
}
}

if (head->value == pivot) {
if (MH == nullptr) {
MH = head;
MT = head;
} else {
MT->next = head;
MT = head;
}
}

if (head->value > pivot){
if (BH == nullptr){
BH = head;
BT = head;
}else{
BT->next = head;
BT = head;
}
}
head = next;
}

if (ST != nullptr){
ST->next = MH;
MT = MT == nullptr ? ST : MT;

  }
if (MT != nullptr){
MT->next = BH;
}
return head = ST == nullptr ? MT == nullptr ? BH : MH : SH;

}

void Print(Node *head)

{
while (head != nullptr) {
std::cout << head->value << std::endl;
head = head->next;
}

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