设为首页 加入收藏

TOP

Leetcode - Insertion Sort List
2015-07-20 17:30:24 来源: 作者: 【 】 浏览:3
Tags:Leetcode Insertion Sort List

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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 1436 Horizontally Visible S.. 下一篇Leetcode_num15_Maximun Subarray

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Linux_百度百科 (2025-12-26 12:51:52)
·Shell 流程控制 | 菜 (2025-12-26 12:51:49)
·TCP/UDP协议_百度百科 (2025-12-26 12:20:11)
·什么是TCP和UDP协议 (2025-12-26 12:20:09)
·TCP和UDP详解 (非常 (2025-12-26 12:20:06)