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

LeetCode Solution-86

时间:2020-02-03 09:43:53      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:head   等于   next   tco   node   nod   性能   leetcode   null   

86. 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.

Example:

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

思路
分别用2个链表存储小于x的值和大于等于x的值,然后将两个链表连接起来。注意要将第二个链表尾节点的下一个设为空,不然会出现链表无限循环的情况。

Solution:

ListNode* partition(ListNode* head, int x) {
    ListNode node1(0), node2(0);
    ListNode *p1 = &node1, *p2 = &node2;
        
    while (head) {
        if (head->val < x)
            p1 = p1->next = head;
        else
            p2 = p2->next = head;
        head = head->next;
    }
    p1->next = node2.next;
    p2->next = NULL;
    return node1.next;
}

性能
Runtime: 8 ms??Memory Usage: 9.2 MB

LeetCode Solution-86

标签:head   等于   next   tco   node   nod   性能   leetcode   null   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12254624.html

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