LeetCode -- Insertion Sort List
2015-10-14 00:06
387 查看
题目描述:
Sort a linked list using insertion sort.
思路:
实现一个插入排序list类,遍历链表逐个添加到list,使用list创建新链表。
实现代码:
Sort a linked list using insertion sort.
思路:
实现一个插入排序list类,遍历链表逐个添加到list,使用list创建新链表。
实现代码:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode InsertionSortList(ListNode head) { if(head == null || head.next == null){ return head; } var list = new SortedNodes(); while(head != null){ list.Add(head.val); head = head.next; } ListNode h = null; ListNode node = null; var c = 0; foreach(var n in list.Nodes){ if(c == 0){ node = new ListNode(n); h = node; }else{ node.next = new ListNode(n); node = node.next; } c++; } return h; } public class SortedNodes{ private IList<int> _nodes; public SortedNodes(){ _nodes = new List<int>(); } public void Add(int n) { for(var i = 0;i < _nodes.Count; i++){ if(n < _nodes[i]){ _nodes.Insert(i,n); return; } } _nodes.Add(n); } public IList<int> Nodes{ get{ return _nodes; } } } }
相关文章推荐
- spark基础练习(未完)
- CSDN周排行第一
- LeetCode -- Happy Number
- LeetCode -- Contains Duplicate
- linux文件权限
- 大数加法和大数减法
- LeetCode – Combination Sum
- mysql rsync方式备份
- 图解django 中间件
- Java基于Scanner对象的简单输入计算功能示例
- iredmail下安装脚本分析(一)---get_all.sh 文件所在目录为PKGS
- exit(-1)或者return(-1)shell得到的退出码为什么是255
- Linux rpm 命令参数使用详解
- linux shell 字符串操作(长度,查找,替换)详解
- linux whatis与whatis database 使用及查询方法(man使用实例)
- linux dev 常见特殊设备介绍与应用(loop,null,zero,full,random)
- linux shell命令快捷获得系统帮助(一)[man-pages定义规范]
- linux shell实现随机数几种方法分享(date,random,uuid)
- linux shell 脚本实现tcp/upd协议通讯(重定向应用)
- linux shell数据重定向(输入重定向与输出重定向)详细分析