关闭

【LeetCode】Insertion Sort List

标签: leetcodeJava
2871人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:339943次
    • 积分:6117
    • 等级:
    • 排名:第4238名
    • 原创:270篇
    • 转载:24篇
    • 译文:0篇
    • 评论:73条
    最新评论