描述
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater
than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater
than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class mylist
{
node *head;
public:
mylist()
{
head = new node();
head->next = NULL;
}
void CreateList(int a[], int n);
void Display();
friend void PartionList(mylist &list, int value);
~mylist();
};
void mylist::CreateList(int a[], int n)
{
node *p = head;
for (int i = 0; i < n; i++)
{
node *q = new node();
q->data = a[i];
p->next = q;
p = q;
}
p->next = NULL;
}
void mylist::Display()
{
node *p = head->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void PartionList(mylist &list, int value)
{
node *pre = list.head;
node *p = list.head->next;
//===
while (p)
{
if (p->data < value)
{
pre = pre->next;
p = p->next;
}
else
{
break;
}
}
//===
while (p)
{
node *temp = p;
while (p&&p->data >= value)//注意先后顺序
{
temp = p;
p = p->next;
}
if (p)
{
temp->next = p->next;
p->next = pre->next;
pre->next = p;
pre = p;
p = temp;
}
}
}
mylist::~mylist()
{
node *p = head;
while (head)
{
head = p->next;
delete p;
p = head;
}
}
int main()
{
//===
const int n = 8;
int a[n] = { 1, 4, 3, 2, 5, 2,8,6 };//代表417593
mylist list;
list.CreateList(a, n);
list.Display();
//===
int value = 4;
PartionList(list, value);
list.Display();
}