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) {
ListNode index = head;
ListNode resulthead = new ListNode(-65535);
while(index != null){
ListNode temp = resulthead;
while(temp.next!=null && temp.next.val < index.val) temp = temp.next;
ListNode newNode = new ListNode(index.val);
newNode.next = temp.next;
temp.next = newNode;
index = index.next;
}
return resulthead.next;
}
};