码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Insertion Sort List

时间:2014-06-21 12:26:49      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

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);
}

 

Leetcode Insertion Sort List,布布扣,bubuko.com

Leetcode Insertion Sort List

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3794939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!