Total Accepted: 66569
Total Submissions: 230248
Difficulty: Medium
Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
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;
}