Using insertion sort on a singly linked list

前端 未结 7 1002
春和景丽
春和景丽 2021-02-06 10:11

So I have an assignment where I\'m giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts b

7条回答
  •  情书的邮戳
    2021-02-06 11:08

    Here is the Java Implementation of Insertion Sort on Linked List:

    • Time Complexity: O(n^2)
    • Space Complexity: O(1) - Insertion sort is In-Place sorting algorithm
    class Solution 
    {
        public ListNode insertionSortList(ListNode head)
        {
            // Initialize partially sorted list
            ListNode dummy = new ListNode(0), prev = dummy, current = head;
    
            while(current != null)
            {
                if(prev.val > current.val)
                    prev = dummy;
    
                // Find the right place to insert current node
                while(prev.next != null && prev.next.val < current.val)
                    prev = prev.next;
    
                // Insert current between prev and prev.next
                ListNode nextNode = current.next;
                current.next = prev.next;
                prev.next = current;
                current = nextNode;
            }
            return dummy.next;
        }
    }
    

提交回复
热议问题