您的位置:首页 > 其它

Insertion Sort List

2016-07-03 00:37 267 查看
Sort a linked list using insertion sort.

Example

Given
1->3->2->0->null
, return
0->1->2->3->null
.

分析:

利用insertion sort的原理,把list A的一个node插入到另一个list B里面,这里关键是list B的尾部的处理。

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
* cnblogs.com/beiyeqingteng/
*/

public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummyNode = new ListNode(Integer.MIN_VALUE);  // a new list

while(head != null) {
ListNode current = dummyNode;
while(head.val > current.val && current.next != null && current.next.val < head.val) {
current = current.next;
}
ListNode next = current.next;
current.next = head;
head = head.next;
current.next.next = next;
}
return dummyNode.next;
}
}


转载请注明出处:cnblogs.com/beiyeqingteng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: