【题目描述】Sort a linked list using insertion sort.对链表使用插入排序
【解题思路】新建一个头节点,遍历原来的链表,对原链表的每个节点找到新链表中适合插入位置的前指针,然后执行插入操作。这种操作链表的题有一个技巧就是新建一个newhead作为head,然后把数据插入到newhead的链表中,最后返回newhead->next。
【考查内容】链表的插入排序
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* newhead = new ListNode(0);
newhead->next = head;//在head前添加一个新头newhead
ListNode* p = head->next;//遍历从第二个node开始
head->next = NULL;//如果后面插入的结点都在head之前,保证排完序的链表结尾指向null
while (p != NULL) {//用p遍历还未排序的链表
ListNode* cur = p;
p = p->next;
ListNode* node = newhead->next;
ListNode* pre = newhead;
while (true) {//用node遍历已排好序的链表,pre表示遍历时当前项的前一项
if (cur->val < node->val) {//在该插入的位置插入cur
pre->next = cur;
cur->next = node;
break;
} else {//还未到插入的位置,继续向后,同时更新pre
pre = node;
node = node->next;
}
if (node == NULL) {//如果插入的位置在链表末尾
pre->next = cur;
cur->next = NULL;
break;
}
}
}
return newhead->next;
}
};