【LeetCode 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

思路

建立兩個鏈表

代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* premin = new ListNode(-1);
        ListNode* premax = new ListNode(-1);
        ListNode* stmin = premin;
        ListNode* stmax = premax; 
        ListNode* cur = head;
        while (cur != NULL) {
            if (cur->val < x) {
                premin->next = cur;
                premin = premin->next;
            }else {
                premax->next = cur;
                premax = premax->next;
            }
            cur = cur->next;
        }
        
        premax->next = NULL;
        premin->next = stmax->next;
        return stmin->next;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章