美文网首页
147. Insertion Sort List

147. Insertion Sort List

作者: juexin | 来源:发表于2017-01-09 19:15 被阅读0次

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

相关文章

  • 147. Insertion Sort List

    题目147. Insertion Sort List Sort a linked list using inser...

  • 147. Insertion Sort List

    题目要求: Sort a linked list using insertion sort.利用插入排序对一个链表...

  • 147. Insertion Sort List

    插入结点 但是 超时了。。 嗯 很蠢的做法 不超时的做法:

  • 147. Insertion Sort List

    思路 插入排序的思想,将未排序的与已知排好序的作比较,进行插入 创建一个链表来作为已知链表(rptr), 比较的是...

  • 147. Insertion Sort List

    题目 Sort a linked list using insertion sort. 思路 这道题花费了最多的时...

  • 147. Insertion Sort List

    Sort a linked list using insertion sort.使用插入排序法排链表。

  • 147. Insertion Sort List

    Sort a linked list using insertion sort.

  • 147. insertion sort list

    Sort a linked list using insertion sort. 这题是用插入排序排序一个链表。插...

  • 147. Insertion Sort List

    对链表进行插入排序。 插入排序的基本思想是,维护一个有序序列,初始时有序序列只有一个元素,每次将一个新的元素插入到...

  • 2018-11-10

    147.Insertion Sort List Sort a linked list using insertio...

网友评论

      本文标题:147. Insertion Sort List

      本文链接:https://www.haomeiwen.com/subject/lvphbttx.html