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.
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.
思路:
将比x小的放到左链表,其它放到右链表。最后将两个链表链接起来。
#include <iostream>
using namespace std;
struct LinkNode
{
int data;
LinkNode *next;
LinkNode(int x):data(x),next(nullptr){}
};
第一次
//LinkNode *patitionList(LinkNode *link,int x)
//{
// LinkNode *dummy_L = new LinkNode(-1);
// LinkNode *dummy_R = new LinkNode(-1);
// LinkNode *tmp = NULL,*tmp_l = NULL,*tmp_r = NULL;
//
// if(NULL == link)
// {
// printf("It is null\n");
// return NULL;
// }
//
// while(link!=NULL)
// {
// tmp = link;//待插入的节点
// link = link->next;
// if(tmp->data < x)
// {
// tmp_l = dummy_L;
// while(tmp_l->next)
// tmp_l = tmp_l->next;//尾插法,找到要插入的节点的前驱
// tmp->next = NULL;
// tmp_l->next = tmp;
// }
// else
// {
// tmp_r = dummy_R;
// while(tmp_r->next)
// tmp_r = tmp_r->next;//尾插法,找到要插入的节点的前驱
// tmp->next = NULL;
// tmp_r->next = tmp;
// }
// }
//
// tmp_l->next->next = dummy_R->next;//将两个链表合并
// tmp_r->next->next = NULL;//将最后一个节点指向NULL
// link = dummy_L->next;
//}
//改进。
//用一个指针初始指向哑节点,插入一个节点后,就移到当前节点上。这个指针始终就指在最后一个节点。这样就不用每次都用while循环去找尾节点。
LinkNode *patitionList(LinkNode *head,int x)
{
LinkNode *dummy_l = new LinkNode(-1);
LinkNode *dummy_r = new LinkNode(-1);
LinkNode *cur,*pre_l,*pre_r;
pre_l = dummy_l;
pre_r = dummy_r;
for(cur = head;cur;cur=cur->next)
{
if(cur->data < x)
{
//pre_l最开始位于哑节点,采用尾插法。插入一个节点,pre_l移到该节点上,始终在当前最后一个节点上。
pre_l->next = cur;
pre_l = cur;
}
else
{
pre_r->next = cur;
pre_r = cur;
}
}
pre_l->next = dummy_r->next;
pre_r->next = NULL;
head = dummy_l->next;
delete dummy_l;
delete dummy_r;
return head;
}
//创建一个链表
struct LinkNode * createList()
{
struct LinkNode * dummy = new LinkNode(-1);
struct LinkNode * head;
struct LinkNode *tmp = dummy;
int array[]={1,3,7,6,5,2,8};
for(int i=0;i<sizeof(array)/sizeof(int);i++)
{
struct LinkNode * p = new LinkNode(array[i]);
//用一个指针初始指向哑节点,插入一个节点后,就移到当前节点上。这个指针始终就指在最后一个节点。这样就不用每次都用while循环去找尾节点。
//while(tmp->next)
//{
//tmp = tmp->next;
//}
tmp->next = p;
tmp = tmp->next;
}
head = dummy->next;
delete dummy;
return head;
}
void showList(struct LinkNode *head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}
void main()
{
int x;
struct LinkNode *head;
head = createList();
showList(head);
printf("Please input the value to patition the list.\n");
if(scanf_s("%d",&x)!=EOF)
{
head = patitionList(head,x);
showList(head);
}
}