C++ code, using quick sort, change the value in ListNode


  • -3
    F
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            if (head == nullptr)
                return nullptr;
                
            vector<int> nums;
            ListNode *p = head;
            while (p != nullptr)
            {
                nums.push_back(p->val);
                p = p->next;
            }
            
            quickSort(nums, 0, nums.size() - 1);
            p = head;
            int i = 0;
            while (p != nullptr && i < nums.size())
            {
                p->val = nums[i++];
                p = p->next;
            }
            return head;
        }
        
        void quickSort(vector<int> &a, int left, int right) {
            if (left < right)
            {
                int i = left, j = right, x = a[i];
                while (i < j)
                {
                    while (i < j && a[j] > x)
                        j--;
                    if (i < j)
                        a[i++] = a[j];
                    
                    while (i < j && a[i] < x)
                        i++;
                    if (i < j)
                        a[j--] = a[i];
                }
                a[i] = x;
                quickSort(a, left, i - 1);
                quickSort(a, i + 1, right);
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.