标签:
Insertion Sort List
问题:
Sort a linked list using insertion sort.
思路:
三行情书 旧旧 新 旧 旧 新
我的代码:
/** * 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 dummy = new ListNode(-1); dummy.next = head; ListNode tail = head; ListNode cur = head.next; while(cur != null) { if(cur.val >= tail.val) { cur = cur.next; tail = tail.next; } else { ListNode first = dummy.next; ListNode pre = dummy; while(cur.val > first.val) { first = first.next; pre = pre.next; } tail.next = cur.next; cur.next = pre.next; pre.next = cur; cur = tail.next; } } return dummy.next; } }
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4337393.html