LeetCode 147 Insertion Sort List(链表插入排序)

147. Insertion Sort List

My Submissions
Total Accepted: 66569  Total Submissions: 230248  Difficulty: Medium

Sort a linked list using insertion sort.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems










这个题目我感觉是有问题的,因为题目传的是一级指针,那么main函数的head应该还是指向的不是有序指针的表头


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>

typedef long long ll;
#define eps 1e-8

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hi"\n)
using namespace std;
#define INF 0x3f3f3f3f
#define N 40005

 struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    void inse(ListNode* p)
    {
        next=p;
    }
};

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
         ListNode * hello;
         if(head==NULL) return head;
         hello=(ListNode*)malloc(sizeof(ListNode));//开一个新的链表头
         hello->next=NULL;
         while(head)//依次奖原链表的节点插入到新的链表合适的位置
         {
               ListNode *pre=hello;
               ListNode *cur=hello->next;
               ListNode *it=head->next;//因为下面会改变head->next,所以提前记录
               while(cur&&cur->val<head->val)
               {
                   pre=pre->next;
                   cur=cur->next;
               }
               pre->next=head;
               head->next=cur;
               head=it;
         }
         ListNode* it=hello;
         hello=hello->next;
         free(it);//释放开始的链表头,表头只是为了方便,没有作用
         return hello;
    }
};

void show(ListNode* head)
{
    while(head)
    {
        printf("%d ",head->val);
        head=head->next;
    }
    printf("\n");
}

int main()
{
    int i,j;
    ListNode* head,*tail;
    head=(ListNode *)malloc(sizeof(ListNode));
    head->val=1;
    head->next=NULL;
    tail=head;
    for(int i=10;i>1;i--)
    {
        ListNode* temp;
        temp=(ListNode *)malloc(sizeof(ListNode));
        temp->val=i;
        temp->next=NULL;
        tail->inse(temp);
        tail=temp;
    }
    show(head);
    Solution ans;
    tail=ans.insertionSortList(head);
    show(tail);
   return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值