码迷,mamicode.com
首页 > 其他好文 > 详细

19.2.23 [LeetCode 86] Partition List

时间:2019-02-23 10:19:25      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:play   null   NPU   equal   int   each   font   col   ssh   

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

题意

把链表按前面的全是小于x的,后面的全是大于等于x的顺序重组

题解

技术图片
 1 class Solution {
 2 public:
 3     ListNode* partition(ListNode* head, int x) {
 4         ListNode*less = new ListNode(0),*lessh=less, *greater = new ListNode(0),*greaterh=greater;
 5         while (head) {
 6             ListNode*after = head->next;
 7             if (head->val < x) {
 8                 less->next = head;
 9                 less = less->next;
10                 less->next = NULL;
11             }
12             else {
13                 greater->next = head;
14                 greater = greater->next;
15                 greater->next = NULL;
16             }
17             head = after;
18         }
19         less->next = greaterh->next;
20         return lessh->next;
21     }
22 };
View Code

我就总爱各种地方有漏洞……面的时候也差不多……惨

19.2.23 [LeetCode 86] Partition List

标签:play   null   NPU   equal   int   each   font   col   ssh   

原文地址:https://www.cnblogs.com/yalphait/p/10421638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!