[LeetCode]148. Sort List

链表排序

Posted by JinFei on March 31, 2020

题目描述

Sort a linked list in O(n log n) time using constant space complexity.

Example1:

  Input: 4->2->1->3
    Output: 1->2->3->4

Example2:

  Input: -1->5->3->4->0
    Output: -1->0->3->4->5

Example3:

  Input: " 3+5 / 2 "
    Output: 5

解题思路

  • 使用冒泡排序
  • 时间复杂度O(n^2)
/**
 * 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;
        }
        ListNode* cur = head;
        while(cur -> next){
            ListNode* pnext = cur -> next;
            while(pnext != nullptr){
                if(cur -> val > pnext -> val){  // 这里其实是 找了一个最小的 放在了cur这里
                    swap(cur -> val, pnext -> val);
                }
                pnext = pnext -> next;
            }
            cur = cur -> next;
        }
        return head;
    }
};