• LeetCode 147. 对链表进行插入排序


    题目描述:

    解法一(头节点另处理):

    /**
     * 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;
            ListNode* pre=head, *cur=head->next;
            while(cur!=NULL){
                ListNode* pp=NULL,*nn=head;
                while(nn!=cur&&nn->val<=cur->val){            //寻找插入位置
                    pp=nn;
                    nn=nn->next;
                }
                if(nn==cur){                                  //原位置不变
                    pre=cur;
                    cur=cur->next;
                }
                else{
                    pre->next=cur->next;                     //取出结点
                    if(nn==head){                            //头节点另处理
                        cur->next=nn;
                        head=cur;
                    }
                    else{                                    //正常插入
                        cur->next=nn;
                        pp->next=cur;
                    }
                    cur=pre->next;
                }
                
            }
            return head;
        }
    };

    解法二(虚拟头节点):

    /**
     * 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;
            ListNode* Vhead=new ListNode(1);
            Vhead->next=head;
            ListNode* pre=head, *cur=head->next;
            while(cur!=NULL){
                ListNode* pp=Vhead,*nn=pp->next;
                while(nn!=cur&&nn->val<=cur->val){            //寻找插入位置
                    pp=nn;
                    nn=nn->next;
                }
                if(nn==cur){                                  //原位置不变
                    pre=cur;
                    cur=cur->next;
                }
                else{
                    pre->next=cur->next;                     //取出结点
                    cur->next=nn;
                    pp->next=cur;
                    cur=pre->next;
                }
            }
            head=Vhead->next;
            delete Vhead;
            return head;
        }
    };
  • 相关阅读:
    jsf web.xml配置
    JSF中Filter的实现
    转码
    facelates标签
    jsf学习笔记注解
    date工具类
    js秒读功能
    w3c document 与 dom4j document转化工具类
    jsf学习笔记ui
    jsf学习笔记拦截器
  • 原文地址:https://www.cnblogs.com/oneDongHua/p/14264009.html
Copyright © 2020-2023  润新知