R_xiaozhu_Q的专栏

love what i'm loving~

【LeetCode】Insertion Sort List

Sort a linked list using insertion sort.

java code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null)
			return head;
		ListNode cur = head.next;
		while(cur != null)
		{
			ListNode tmp = head;
			while(tmp.val < cur.val && tmp != cur)//first node whose value greater than current value
				tmp = tmp.next;
			if(tmp != cur)
			{
				while(tmp != cur)
				{
					int tmpvalue = tmp.val;
					tmp.val = cur.val;
					cur.val = tmpvalue;
					tmp = tmp.next;
				}
			}
			cur = cur.next;
		}
		return head;
    }
}


阅读更多
文章标签: leetcode Java
个人分类: LeetCode
上一篇MapReduce 工作机制
下一篇【LeetCode】Binary Tree Postorder Traversal
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭