Sort a linked list using insertion sort.
我的理解是通过插入排序法对链表进行排序的操作:
在链表中主要由两个指针,一个是pre指向当前比较的节点的前一个节点,还有一个是pCur是代表当前节点
自己写得比较繁杂,看到别人写得比较简单,可以参考
我的理解是通过插入排序法对链表进行排序的操作:
在链表中主要由两个指针,一个是pre指向当前比较的节点的前一个节点,还有一个是pCur是代表当前节点
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(!head || !head->next)
{
return head;
}
ListNode * pre = head;
ListNode * pCur = head->next;
while(pCur)
{
while (pre->next != pCur)
{
pre = pre->next;
}
if(pCur->val >= pre->val)
{
pCur = pCur->next;
continue;
}
ListNode * pCurNext = pCur->next;
pre->next = pCurNext;
ListNode * p = head;
while(p != pCur)
{
if(pCur->val <= p->val)
{
int temp = p->val;
p->val = pCur->val;
pCur->val = temp;
pCur->next = p->next;
p->next = pCur;
break;
}
p = p->next;
}
if (pCurNext)
{
pCur = pCurNext;
}
else
{
pCur = NULL;
}
}
return head;
}
};
int main()
{
ListNode head[4];
head[0].val = 4;
head[1].val = 2;
head[2].val = 1;
head[3].val = 3;
head[0].next = &head[1];
head[1].next = &head[2];
head[2].next = &head[3];
head[3].next = NULL;
Solution cS;
ListNode * result = cS.insertionSortList(head);
while (result)
{
cout<<result->val;
result = result->next;
}
return 0;
}
自己写得比较繁杂,看到别人写得比较简单,可以参考
class Solution
{
public:
ListNode *insertionSortList(ListNode *head)
{
if(head==NULL || head->next==NULL) return head;
ListNode *cur=head;
ListNode *helper=new ListNode(0);
ListNode *pre;
while(cur)
{
ListNode *next=cur->next;
pre=helper;
while(pre->next!=NULL && pre->next->val<cur->val)
{
pre=pre->next;
}
cur->next=pre->next;
pre->next=cur;
cur=next;
}
return helper->next;
}
};
创建了一个新的链表,把符合要求的节点一个个复制到这个新链表当中
利用pre节点创造了新的链表,一直是保持有个新的链表结构
pre->......->null
cur->......->null
while循环中就是比较cur对应的节点在pre当中的位置,或者直接到pre的最后面了,然后将cur直接插入进入pre对应的链表当中