/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*void insertionSort(int *a,int n){
for(int j = 2;j<n;j++){
i = j-1;
int key = a[j];
while(i>=0&&a[i]>key){
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
}*/
//将head作为有序链表,将head->next作为待插入的链表
class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
if(head == NULL||head->next ==NULL) return head;
//if(!head) return head;
ListNode temp(0);//define a dummyHead
ListNode *p,*q,*t;
while(head)
{
p = &temp;
q = p->next;
t = head;
head = head->next;
while(q&&q->val<t->val)
{
p = p->next;
q = q->next;
}
p->next = t;
t->next = q;
}
return temp.next;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*void insertionSort(int *a,int n){
for(int j = 2;j<n;j++){
i = j-1;
int key = a[j];
while(i>=0&&a[i]>key){
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
}*/
//将head作为有序链表,将head->next作为待插入的链表
class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
if(head == NULL||head->next ==NULL) return head;
//if(!head) return head;
ListNode temp(0);//define a dummyHead
ListNode *p,*q,*t;
while(head)
{
p = &temp;
q = p->next;
t = head;
head = head->next;
while(q&&q->val<t->val)
{
p = p->next;
q = q->next;
}
p->next = t;
t->next = q;
}
return temp.next;
}
};
本文介绍了一种基于链表的插入排序算法实现方法,并通过具体的C++代码示例详细展示了如何将一个链表通过插入排序的方式变为有序链表的过程。
295

被折叠的 条评论
为什么被折叠?



