码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - Insertion Sort List

时间:2014-10-12 09:08:27      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   io   os   java   for   sp   on   cti   amp   

 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;
	}
}


Leetcode - Insertion Sort List

标签:style   io   os   java   for   sp   on   cti   amp   

原文地址:http://blog.csdn.net/tspatial_thunder/article/details/40013855

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!