题目:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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>
#include <vector>
#include <string>
using namespace std;
typedef struct list_node List;
struct list_node
{
struct list_node* next;
int value;
};
void print_list(List* list)
{
List* tmp=list;
while(tmp != NULL)
{
cout<<tmp->value<<endl;
tmp = tmp->next;
}
}
/*
初始化List 将从1~n的数字插入到链表中
*/
void Init_List(List*& head,int* array,int n)
{
head = NULL;
List* tmp;
List* record;
for(int i=1;i<=n;i++)
{
tmp = new List;
tmp->next = NULL;
tmp->value = array[i-1];
if(head == NULL)
{
head = tmp;
record = head;
}
else
{
record->next = tmp;
record = tmp;
}
}
}
int Len_list(List* list)
{
if(list == NULL)
return 0;
else
return Len_list(list->next)+1;
}
/*类似于快速排序的分割*/
void PartitionList(List*& list,int key)
{
if(list == NULL)
return ;
List* record,*cur,*pre,*tmp;
record = NULL;
cur = list;
pre = NULL;
while(cur != NULL)
{
if(cur->value < key) //插入到pre之后 注意区分第一个的情况
{
tmp = cur->next;
if(pre == NULL)
pre = cur;
if(record == NULL)
{
record = list;
list = cur;
cur->next = record;
record = cur;
pre->next = tmp;
}
else
{
if(pre != record)
{
cur->next = record->next;
record->next = cur;
pre->next = tmp;
record = cur;
}
else
record = pre = cur;
}
cur = tmp;
}
else //
{
pre = cur;
cur = cur->next;
}
}
}
int main()
{
int array[]={5,1,2,7,8,4,3,6,10,9};
//int array[]={1,4,3,2,5,2};
List* list;
Init_List(list,array,sizeof(array)/sizeof(int));
PartitionList(list,5);
print_list(list);
return 0;
}
思路:这里仍然借助一个指针来更加容易的解决问题
List* PartationList(List* list,int key)
{
List* head = new List;
head->next = list;
List* temp = head;
List* pre=head,*cur =list,*next;
while(cur != NULL)
{
next = cur->next;
if(cur->value < key)
{
pre->next = next;
cur->next = temp->next;
temp->next = cur;
temp = cur;
cur = next;
}
else
{
pre = cur;
cur = next;
}
}
return head->next;
}
ps:其实这个题目使用伪指针来串引真个链表是非常合适的,但是为了将某一个指针插入到这个链表中,最合适的方法就是插入当前指针的下一个元素,使用的思想还是快排分割的思想,对于插入cur->next这个指针,那么就会变得非常的方便