86. 分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
 
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 
 
 
新建两个节点
 
 
 
 
 
 
 
 
 
 1 class Solution {
 2 public:
 3     ListNode* partition(ListNode* head, int x) {
 4         ListNode less_head(0);//临时头节点,接收小于 x 的节点
 5         ListNode more_head(0);
 6         ListNode *less_ptr = &less_head;
 7         ListNode *more_ptr = &more_head;
 8         
 9         while (head) {
10             if (head->val < x) {//向后移动,并且指向新节点
11                 less_ptr->next = head;
12                 less_ptr = head;
13             } else {
14                 more_ptr->next = head;
15                 more_ptr = head;
16             }
17             head = head->next;
18         }
19         less_ptr->next = more_head.next;//连成一个新链表
20         more_ptr->next = NULL;
21         return less_head.next;
22     }
23 };

 

测试
 1 int main(int argc, const char * argv[]) {
 2     ListNode a(1);
 3     ListNode b(4);
 4     ListNode c(3);
 5     ListNode d(2);
 6     ListNode e(5);
 7     ListNode f(2);
 8     a.next = &b;
 9     b.next = &c;
10     c.next = &d;
11     d.next = &e;
12     e.next = &f;
13     
14     Solution solve;
15     ListNode *head = solve.partition(&a, 3);
16     while (head) {
17         cout <<head->val<<endl;
18         head = head->next;
19     }
20     
21     return 0;
22 }
View Code

 

posted @ 2019-11-09 15:15  0x8023  阅读(94)  评论(0编辑  收藏  举报