zoukankan      html  css  js  c++  java
  • [LeetCode] Insertion Sort List

    Sort a linked list using insertion sort.

    Solution:

    新建链表,逐个插入即可~

    /**
     * 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) {
            if(head == NULL || head -> next == NULL) 
                return head; //0 and 1 nodes return itself
            
            ListNode *sortedHead = new ListNode(head -> val), *srcNode = head -> next;
            while(srcNode != NULL)
            {
                ListNode *preNode = NULL, *curNode = sortedHead;
                 while(curNode != NULL)
                {
                    if(curNode -> val < srcNode -> val)
                     {
                         preNode = curNode;
                            curNode = curNode -> next;
                    }
                    else
                        break;
                }
                if(preNode != NULL)
                {
                    preNode -> next = new ListNode(srcNode -> val);
                    preNode -> next -> next = curNode;
                }
                else
                {
                    ListNode *tmp = sortedHead;
                    sortedHead = new ListNode(srcNode -> val);
                    sortedHead -> next = tmp;
                }
                srcNode = srcNode -> next;
            }
            
            return sortedHead;
        }
    };
  • 相关阅读:
    移动app测试
    centos7中tomcat安装步骤
    linux下搭建数据库
    Linux 学习笔记
    vi编辑器 使用表
    python-Xml 实战
    python-Excel 实战
    手写HashMap
    volatile关键字解析
    两个栈实现队列——优化版
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3598185.html
Copyright © 2011-2022 走看看