美文网首页程序员
86. Partition List

86. Partition List

作者: Nautilus1 | 来源:发表于2017-11-09 17:18 被阅读0次

    题目描述:给一个链表和一个值 x ,使得所有比 x 小的值都在比 x 大的值的结点前面,保持两部分的原始相对位置。如:

    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5

    分析:设两指针分别链接比 x 大的结点和比 x 小的结点,最后用链接小于 x 结点的链表链接大于 x 结点的链表即可。时间复杂度O(n),空间O(1)。

    代码

    /**
     * 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 l(-1);
            ListNode r(-1);
            auto lc = &l;        //指向小于 x 的链表尾
            auto rc = &r;
            for (ListNode *cur = head; cur; cur = cur->next)
            {
                if (cur->val < x)
                {
                    lc->next = cur;
                    lc = cur;
                }
                else
                {
                    rc->next = cur;
                    rc = cur;
                }
            }
            lc->next = r.next;
            rc->next = nullptr;
            return l.next;
        }
    };
    

    相关文章

      网友评论

        本文标题:86. Partition List

        本文链接:https://www.haomeiwen.com/subject/igkmmxtx.html