leetcode - [5]Insertion Sort List
Sort a linked list using insertion sort.
思路:插入排序
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x): val(x), next(NULL) {} }; class Solution { public: ListNode *insertionSortList(ListNode *head) { if (!head || head->next == NULL) { return head; } ListNode *cur, *prev, *next, *p; cur = head->next; head->next = NULL; while (cur) { p = head; prev = NULL; while ((p != NULL) && (p->val < cur->val)) { prev = p; p = p->next; } next = cur->next; if (p != NULL) { if (prev != NULL) { cur->next = p; prev->next = cur; } else { cur->next = p; head = cur; } } else { cur->next = NULL; prev->next = cur; } cur = next; } return head; } }; int main(int argc, char *argv[]) { ListNode *p = new ListNode(4); p->next = new ListNode(0); p->next->next = new ListNode(-1); p->next->next->next = new ListNode(-1); Solution *solution = new Solution(); p = solution->insertionSortList(p); while (p) { cout << p->val << endl; p = p->next; } return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步