您的位置:首页 > 其它

Leetcode - Insertion Sort List

2014-10-12 06:27 309 查看
 It is quite a basic problem.  However I spent half an hour solving it and made two mistakes. Guess it's because I haven't written some fundamental data structures like linked list for a while and kind of get lost. I should practice
these questions more. 

public class Solution {
public ListNode insertionSortList(ListNode head) {

if (head == null || head.next == null)
return head;

ListNode cNode = head.next;
ListNode prevcNode = head;

while (cNode != null) {
if (cNode.val <= head.val) {
prevcNode.next = cNode.next;
cNode.next = head;
head = cNode;

cNode = prevcNode.next;
}

else {

ListNode tNode = head;
while( tNode.next != cNode &&tNode.next.val < cNode.val)
{
tNode = tNode.next;
}

if(tNode.next == cNode)
{
prevcNode = cNode;
cNode = cNode.next;
}

else
{
prevcNode.next = cNode.next;
cNode.next = tNode.next;
tNode.next = cNode;

cNode = prevcNode.next;
}
}
}

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