zoukankan      html  css  js  c++  java
  • Leetcode Insertion Sort List

    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);
    }
  • 相关阅读:
    玲珑杯 1035 D-J
    多项式exp
    Thanks to World
    【uoj#191.】Unknown
    【bzoj4534】基础排序算法练习题
    【bzoj4596】黑暗前的幻想乡
    【bzoj2893】征服王
    【bzoj3876】支线剧情
    【bzoj4283】魔法少女伊莉雅
    【bzoj1822】冷冻波
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3794939.html
Copyright © 2011-2022 走看看