The tough part of this question is to organize the reference well. For example, the newHead is a separate reference of original head. Watch out no that! All secondary comparisons are based on the newHead and insert into the "new" list.
/**
* 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 node = head.next;
ListNode newHead = new ListNode(head.val);
while(node != null){
ListNode nextNode = node.next;
if(node.val <= newHead.val){
node.next = newHead;
newHead = node;
}else{
ListNode lp = newHead;
while(lp.next != null){
if(lp.val < node.val && lp.next.val >= node.val){
ListNode temp = lp.next;
lp.next = node;
node.next = temp;
break;
}
lp = lp.next;
}
if(lp.next == null && node.val >= lp.val){
lp.next = node;
node.next = null;
}
}
node = nextNode;
}
return newHead;
}
}
没有评论:
发表评论