您的位置:首页 > 其它

LeetCode -- Insertion Sort List

2015-10-14 00:06 369 查看
题目描述:
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;
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: