Wednesday, November 13, 2013

Insertion Sort List

Sort a linked list using insertion sort.

Solution: nothing but pointer manipulation; check here for insertion sort.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head==NULL || head->next==NULL)
            return head;
        ListNode* outerPre = head;
        ListNode* outerCur = head->next;
        while(outerCur!=NULL){
            ListNode* pre = NULL;
            ListNode* cur = head;
            while(cur!=outerCur && cur->val<=outerCur->val){
                pre=cur;
                cur=cur->next;
            }
            if(cur->val>outerCur->val){
                ListNode* tmp = outerCur->next;
                outerPre->next=tmp;
                if(pre==NULL){
                    outerCur->next = head;
                    head=outerCur;
                    outerCur=tmp;
                }
                else{
                    outerCur->next = cur;
                    pre->next=outerCur;
                    outerCur=tmp;
                }
            }
            else{
                outerPre=outerCur;
                outerCur=outerCur->next;
            }
        }
        return head;
    }
};

No comments:

Post a Comment