首页 > 学院 > 开发设计 > 正文

leetcode之insertion-sort-list

2019-11-06 07:40:53
字体:
来源:转载
供稿:网友

题目描述

Sort a linked list using insertion sort. 思路:新建一个链表,遍历原链表,将每个节点加入新链表正确的位置。

class Solution {public: ListNode *insertionSortList(ListNode *head) { if(!head || !head ->next) { return head; } list<int> v; for(ListNode *p = head; p!=NULL; p = p->next) { v.push_back(p->val); //把链表的元素存储到线性表 } v.sort(); //直接调用sort进行排序 for(ListNode *p = head; p != NULL; p = p->next) { p ->val = v.front(); //把线性表排好序的序列一个个赋值给链表 v.pop_front(); } return head; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表