[leet code] Insertion Sort List

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 10:36

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;    }}

0 0
原创粉丝点击