147. Insertion Sort List
Last updated
Last updated
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode node = new ListNode(-1);
while(head != null) {
ListNode curr = node;
while(curr.next != null && curr.next.val < head.val) {
curr = curr.next;
}
ListNode tmp = head.next;
head.next = curr.next;
curr.next = head;
head = tmp;
}
return node.next;
}
}