Leetcode Sort List

来源:互联网 发布:淘宝店铺层级怎么计算 编辑:程序博客网 时间:2024/04/27 05:58

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

单链表排序问题,下面用插入排序的方法。

/** * 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) {ListNode* p = new ListNode(0);p->next = NULL;ListNode *q = p;if (head == NULL)return head;else{p->next = head;head = head->next;p->next->next = NULL;}while (head != NULL){p = q;while (p->next != NULL){if (p->next->val >= head->val){break;}p = p->next;}//insert head point nodeListNode *temp = head;head = head->next;temp->next = p->next;p->next = temp;}return q->next;}};


0 0