Leetcode 86. Partition List

https://leetcode.com/problems/partition-list/description/
https://discuss.leetcode.com/category/94/partition-list
来自@yeze322 的简洁解法

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.

第一想法就是先找到第一个大于或等于3的元素的前一个first,然后继续遍历,若后续有小于3的元素,则插入到first后,在原链表上调整。
通过新增一个tempHead,使得能在head前插入。

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if (!head) return head;

        ListNode* tempHead = new ListNode(head->val);
        tempHead->next = head;

        ListNode* first = tempHead;
        while (first->next != NULL && first->next->val < x) {
            first = first->next;
        }

        ListNode* pre = first;
        ListNode* next = first->next;
        while (next != NULL) {
            if (next->val < x) {
                // 要把next插入到first后
                // 先把pre指向next->next保证后续链表不断
                pre->next = next->next;
                // 然后独立出来的next,
                // 将next指向first->next
                // 保证next可以指向first后面的链表
                next->next = first->next;
                // 将first指向next完成插入
                first->next = next;
                // 重置next
                next = pre->next;
                // 重置first
                first = first->next;
            } else {
                pre = next;
                next = next->next;
            }
        }

        return tempHead->next;
    }
};

不过还有更简单的直接遍历,维护小于x的列表和大于x的列表,最后拼起来然后,是真的简洁…

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode left(0), right(0);
        ListNode *l = &left, *r = &right;

        while(head){
            ListNode* & ref = head->val < x ? l : r;
            ref->next = head;
            ref = ref->next;

            head = head->next;
        }
        l->next = right.next;
        r->next = NULL;
        return left.next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值