Q:
Sort a linked list using insertion sort.
Solution:
/**
* 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)
return head;
ListNode cur = head.next;
while (cur != null) {
ListNode temp = head;
while (temp.val <= cur.val && temp != cur)
temp = temp.next;
if (temp != cur) {
while (temp != cur) {
int tempvalue = temp.val;
temp.val = cur.val;
cur.val = tempvalue;
temp = temp.next;
}
}
cur = cur.next;
}
return head;
}
}