Leetcode 86.分隔链表

分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3

输出: 1->2->2->4->3->5

 1 class Solution{
 2     public:
 3     ListNode *partition(ListNode *head,int x){
 4         ListNode *dummy=new ListNode(-1);
 5         dummy->next=head;
 6         ListNode *pre=dummy,*cur=head;
 7         while(pre->next&&pre->next->val<x) pre=pre->next;
 8         cur=pre;
 9         while(cur->next){
10             if(cur->next->val<x){
11                 ListNode *tmp=cur->next;
12                 cur->next=tmp->next;
13                 tmp->next=pre->next;
14                 pre->next=tmp;
15                 pre=pre->next;
16             }else{
17                 cur=cur->next;
18             }
19         }
20         return dummy->next;
21     }
22 };

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10163065.html