题目:给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头 。 思路: 三个指针, tmphead用来寻找插入合适位置; pre负责指向新元素,last 负责指向新元素的前一元素
先用pre和last比较pre指向的元素是否需要执行插入操作
当需要插入时,tmphead指针每次都会从头查找合适位置,
找到合适位置后就重新连接节点关系
ListNode*insertionSortList(ListNode *head)
{
_dummyHead->next=head;
ListNode*last=head;
ListNode*tmphead=_dummyHead;
ListNode*pre=head->next;
while(pre)
{
if(last->val<pre->val)
{
pre=pre->next;
last=last->next;
continue;
}
tmphead=_dummyHead;
while(tmphead->next->val<pre->val)
{
tmphead=tmphead->next;
}
last->next=pre->next;
pre->next=tmphead->next;
tmphead->next=pre;
pre=last->next;
}
return head;
}
测试代码:
#include<iostream>
using namespace std;
class Solution
{
public:
struct ListNode
{
int val;
struct ListNode*next;
ListNode(int val):val(val),next(nullptr){}
};
ListNode*addAtHead(int val)
{
ListNode* newNode = new ListNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
return _dummyHead->next;
}
ListNode*addeare(int val)
{
ListNode* newNode = new ListNode(val);
ListNode* pre=_dummyHead;
while(pre->next!=nullptr)
{
pre=pre->next;
}
pre->next=newNode;
return _dummyHead->next;
}
void printLinkedList()
{
ListNode* cur = _dummyHead;
while (cur->next != nullptr)
{
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
ListNode*insertionSortList(ListNode *head)
{
_dummyHead->next=head;
ListNode*last=head;
ListNode*tmphead=_dummyHead;
ListNode*pre=head->next;
while(pre)
{
if(last->val<pre->val)
{
pre=pre->next;
last=last->next;
continue;
}
tmphead=_dummyHead;
while(tmphead->next->val<pre->val)
{
tmphead=tmphead->next;
}
last->next=pre->next;
pre->next=tmphead->next;
tmphead->next=pre;
pre=last->next;
}
return head;
}
ListNode* _dummyHead= new ListNode(-1);
};
int main()
{
Solution s,s1;
s.addeare(4);
s.addeare(2);
s.addeare(1);
Solution::ListNode*l1=s.addeare(3);
s.printLinkedList();
Solution:: ListNode*head=s.insertionSortList(l1);
s.printLinkedList();
return 0;
}
|