[leet code] Insertion Sort List

Sort a linked list using insertion sort.

=====================

Analysis:

Idea is to implement the insertion sort from array to linked list.  Basic idea of insertion sort is that, examine array elements one by one, assuming the previous examined elements have been sorted.  Therefore, when examining element i, algorithm would compare it to its previous elements, i,e, element i-1, i-2... 1.  If there ith element < one of its previous elements (say kth element), then insert ith element in front of the kth element.

Applying this algorithm to linked list, our program also examine the nodes in given linked list one by one.  Then for each examining node, compare it with all its previous nodes (from the first node to its closest node), if examining node < any of its previous node, say kth node, then remove examining node from current position and insert it in front of kth node.  

Note that to insert a node in linked list, our program always need to record the previous node of the node we are examining, and handle the .next pointer appropriately.

/**
 * 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 null;
        
        ListNode fakeNode = new ListNode(0); // used to store the resulting head node
        fakeNode.next = head; // initial resulting head node
        
        ListNode preExamNode = head;
        ListNode examNode = head.next;
        
        while(examNode!=null){
            ListNode preNode = fakeNode; 
            ListNode node = preNode.next; 
            
            // compare examining node to all its previous nodes to find out the insertion position
            while(node!=examNode && node.val<=examNode.val){
                preNode = node;
                node = node.next;
            }
            
            if(node!=examNode) { // insertion position found -> insert
                preExamNode.next = examNode.next;
                examNode.next = node;
                preNode.next = examNode;
                //!! reset examNode (position of original examNode has been changed)!!
                examNode = preExamNode.next; 
            }else{// value of examining node >= all its previous nodes -> process next
                preExamNode = preExamNode.next;
                examNode = examNode.next;
            }
        }
        return fakeNode.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值