147. Insertion Sort List

2017-01-09  本文已影响0人  juexin

Sort a linked list using insertion sort.

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(head == NULL||head->next == NULL)
          return head;
        ListNode* newhead = new ListNode(-1);
        newhead->next = head;
        
        ListNode* p = head->next;
        head->next = NULL;//如果后面插入的结点都在head之前,保证排完序的链表结尾指向NULL
        
        while(p != NULL)
        {
            ListNode* cur = p;  //继续从头开始,扫描指针
            p = p->next;
            
            ListNode* pre = newhead;//创建的新的链表
            ListNode* node = newhead->next;
            
            while(true)
            {
                if(cur->val<node->val)
                {
                    pre->next = cur; //插入结点
                    cur->next = node;
                    break;
                }
                else
                {
                   pre = node; //查找下一个结点进行比较
                   node = node->next;
                }
                
                if(node == NULL)
                {
                    pre->next = cur;
                    cur->next = NULL;
                    break;
                }
            }
            
        }
        
       return newhead->next; 
    }
};
上一篇 下一篇

猜你喜欢

热点阅读