题目:Sort a linked list using insertion sort.(其实就是写一个直接插入排序)
但我的代码有问题,求大神指出错误在哪?
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct listnode ListNode;
struct listNode {
int val;
ListNode *next;
};
struct ListNode* insertionSortList(struct ListNode* head) {
if(head==NULL)
return NULL;
ListNode* newHead= (ListNode *)malloc(sizeof(ListNode));
newHead->next=head;
int i,j,tmp;
for(ListNode* p=head->next,*prep=head;p;prep=p,p=p->next)
{
tmp=p1->val;
p2=p1;
for(ListNode *cur=newHead;cur->next!=p;cur=cur->next)
{
if(cur->next->val > p->val)
{
prep->next=p->next
cur->next=p;
p=prep;
break;
}
}
}
ListNode* result = newHead->next;
delete newHead;
return result;
}