题目 对链表进行插入排序
3
题解 插入排序
链表的插入排序,重点在于记录前一个和后一个节点,链表之间的关系处理!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head || head -> next == nullptr)
return head;
//建立头头节点
ListNode* dummy = new ListNode(0);
//记录前一个结点和下一个结点
ListNode* pre,*nex;
while(head){
nex = head -> next;
pre = dummy;
while(pre ->next != nullptr && pre -> next -> val < head -> val){
pre = pre -> next;
}
head -> next = pre -> next;
pre -> next = head;
head = nex;
}
return dummy -> next;
}
};