LeetCode/solutions/86. Partition List.md
2019-03-11 23:20:32 +08:00

1.3 KiB
Raw Blame History

86. Partition List

思路

题目要求将链表中小于x的元素移动最前面来要求保持元素间的相对位置不变。
我们可以从前往后遍历链表将小于x的节点取出来按照顺序组成一个新的链表遍历完成后将这个新链表放在剩下的链表之前即可。 为了方便处理我们定义新的链表的头结点为small_head,剩下的链表的头结点为big_head然后用指针small指向当前新链表的最后一个节点用big指向当前剩余链表的最后一个节点。
时间复杂度O(n)空间复杂度O(1)

C++

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode *small_head = new ListNode(-1), *big_head = new ListNode(-1);
        ListNode *small = small_head, *big = big_head;
        while(head){
            if(head -> val < x){
                small -> next = head;
                head = head -> next;
                small  = small -> next;
            }
            else{
                big -> next = head;
                head = head -> next;
                big = big -> next;
            }
        }
        small -> next = big_head -> next; // 将这个新链表放在剩下的链表之前
        big -> next = NULL;
        return small_head -> next;
    }
};