86. Partition List

Problem:

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

posted @ 2020-02-03 09:05  littledy  阅读(78)  评论(0编辑  收藏  举报