Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
解法:设置3个指针:应插入位置的前一个节点first、当前处理节点third和其前一个节点second,设置辅助节点help指向头节点。然后从头节点的next节点开始遍历,一个个插入正确位置即可。注意在插入到新位置之前需要链接好second和third->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* help = new ListNode(0); help->next = head; ListNode *second = head, *third = head->next; while (third != NULL) { ListNode* first = help; if (third->val < second->val) { while (first->next->val <= third->val) // 找到插入点 first = first->next; second->next = third->next; // 链接断开点 third->next = first->next; // 插入到新的位置 first->next = third; third = second->next; // 前移一个节点 } else { // 前移一个节点 second = third; third = third->next; } } return help->next; } };
时间: 2024-10-29 20:01:22