[leetcode] 【链表】86. Partition List

原创 2016年05月30日 16:43:35

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,
Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.


题意

给定一个值x,把链表中小于x的值放到大于等于x的值之前。即
Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.

同时,两部分的节点要保持原来链表的节点顺序。

题解

创建两个链表,一个存储小的,一个存储大于等于的。
最后把两个链表相连即可。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode small(-1);
        ListNode big(-1);
        auto small_p=&small;
        auto big_p=&big;
        for(ListNode *cur=head;cur;cur=cur->next)
        {
            if(cur->val<x)
            {
                small_p->next=cur;
                small_p=cur;
            }
            else
            {
                big_p->next=cur;
                big_p=cur;
            }
        }
        big_p->next=NULL;
        small_p->next=big.next;
        return small.next;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

LeetCode(86) Partition List

题目Given a linked list and a value x, partition it such that all nodes less than x come before nodes ...

LeetCode 86 Partition List

LeetCode 86 Partition List

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

[LeetCode]86.Partition List

【题目】 Given a linked list and a value x, partition it such that all nodes less than x come before n...

leetcode[86]:Partition List

Partition ListGiven a linked list and a value x, partition it such that all nodes less than x come b...

Leetcode 86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr...

leetcode || 86、Partition List

problem: Given a linked list and a value x, partition it such that all nodes less than x come ...

Leetcode——86. Partition List

题目Given a linked list and a value x, partition it such that all nodes less than x come before nodes ...

Leetcode 86. Partition List(链表划分)

Partition List(链表划分)

LeetCode-86. Partition List (JAVA)分区链表

LeetCode-86. Partition List (JAVA)分区链表

[LeetCode-86] Partition List (链表数据分区)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)