首页 > 代码库 > leetcode链表--11、partition-list(链表分区)

leetcode链表--11、partition-list(链表分区)

题目描述
 
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,Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5
 
解题思路:.本题目是将小于x的放在左侧,大于等于x的放在后面,且相对顺序不变
1)定义两个链表   p存小于x的  q存大于等于x的
2)存完后q->next =  NULL
3)p1->next = qhead->next;
 1 #include <iostream>
 2 #include <malloc.h>
 3 using namespace std;
 4 struct ListNode {
 5     int val;
 6     ListNode *next;
 7     ListNode(int x) : val(x), next(NULL) {}
 8 };
 9 class Solution {
10 public:
11     //定义两个链表  1个存小于x的  一个存大于等于x的
12     //连接两个链表
13     ListNode *partition(ListNode *head, int x) {
14         ListNode *phead = new ListNode(0);
15         ListNode *qhead = new ListNode(0);
16         ListNode *p = phead;
17         ListNode *q = qhead;
18         while(head != NULL)
19         {
20             if(head->val < x)
21             {
22                 p->next = head;
23                 p = p->next;
24             }
25             else
26             {
27                 q->next = head;
28                 q = q->next;
29             }
30             head = head->next;
31         }
32         q->next = NULL;//别忘记给q之后的链表断开,否则无限循环
33         p->next = qhead->next;
34         return phead->next;
35     }
36 };
37 ListNode *CreateList(int n)
38 {
39     ListNode *head;
40     ListNode *p,*pre;
41     int i;
42     head=(ListNode *)malloc(sizeof(ListNode));
43     head->next=NULL;
44     pre=head;
45     for(i=1;i<=n;i++)
46     {
47         p=(ListNode *)malloc(sizeof(ListNode));
48         cin>>p->val;
49         pre->next=p;
50         pre=p;
51     }
52     p->next=NULL;
53 
54     return head->next;
55 }
56 /*-------------------------输出链表-----------------------------------*/
57 void PrintList(ListNode *h)
58 {
59     ListNode *p;
60 
61     p=h;//不带空的头结点
62     while(p)
63     {
64         cout<<p->val<<" ";
65         p=p->next;
66         cout<<endl;
67     }
68 }
69 int main()
70 {
71     int n1;
72     int x;
73     ListNode *h1;
74     cout<<"输入链表1的结点数目"<<endl;
75     cin>>n1;
76     h1 = CreateList(n1);
77     cout<<"链表1为:"<<endl;
78     PrintList(h1);
79     cout<<"输入x"<<endl;
80     cin>>x;
81     Solution s;
82     h1 = s.partition(h1,x);
83     cout<<"分区后链表1为:"<<endl;
84     PrintList(h1);
85     return 0;
86 }

技术分享

leetcode链表--11、partition-list(链表分区)