【面试题 & LeetCode 148】单链表排序

插入排序

/**
 * 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 == NULL || head->next == NULL) return head;
        ListNode* p = head->next;
        
        ListNode* pHead = new ListNode(0);
        pHead->next = head;
        ListNode* nxt = head;
        
        while(p != NULL) {
            ListNode* tmp = pHead->next;
            ListNode* pre = pHead;
            while(tmp != p && p->val >= tmp->val) {
                tmp = tmp->next;
                pre = pre->next;
            }
            if (tmp == p) {
                nxt = p;
            }else {
                nxt->next = p->next;
                pre->next = p;
                p->next = tmp;
            }
            p = nxt->next;
        }
        
        return pHead->next;
    }
};

归并排序

/**
 * 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 == NULL || head->next == NULL) return head;
        ListNode* fast = head->next;
        ListNode* slow = head;
        
        while(fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode* mid = slow->next;
        slow->next = NULL;
        return merge(sortList(head), sortList(mid));
    }
    
    ListNode* merge(ListNode* head1, ListNode* head2) {
        ListNode* head = new ListNode(0);
        ListNode* tmp = head;
        while(head1 != NULL && head2 != NULL) {
            if (head1->val > head2->val)
                swap(head1, head2);
            tmp->next = head1;
            head1 = head1->next;
            tmp = tmp->next;
        }
        if (head2 != NULL) tmp->next = head2;
        return head->next;
    }
};

怎么做多少遍都不记得。
枯了。

发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105624087