Leetcode Insertion Sort List

OpenSoucre發表於2014-06-18

Sort a linked list using insertion sort.

單連結串列的插入排序, 考查的時單連結串列指標的斷開和插入操作

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x), next(NULL){}
};

void printList(ListNode* head){
    while(head!=NULL){
        cout<<"->"<<head->val;
        head = head->next;
    }
    cout<<endl;
}

ListNode *insertionSortList(ListNode *head){
    if(head == NULL ||  head->next == NULL) return head;
    ListNode *newHead = new ListNode(-1);
    newHead->next = head;    
    ListNode *pre = head,*p = head->next;    
    while(p!=NULL){
        ListNode *q = newHead;
        while(q->next!=p){
            if(q->next->val >= p->val ){
                pre->next = p->next;
                p->next = q->next;
                q->next = p;
                p=pre->next;
                break;
            }else{
                q = q->next;
            }
            
        }
        if(q->next == p) {
            pre = p;
            p = p->next;
        }
    }
    ListNode *res = newHead->next;
    delete newHead;
    return res;
}

int main(){
    ListNode* head = new ListNode(3);
    ListNode* node1 = new ListNode(2);
    ListNode* node2 = new ListNode(4);
    head->next = node1;
    node1->next = node2;
    ListNode *a = insertionSortList(head);
    cout<<"ans:"<<endl;
     printList(a);
}

 

相關文章