• OJ练习10——T21 Merge Two Sorted Lists


    合并有序链表,链表结构已给出。

    要求返回的链表由原链表的节点构成,不再重新创建节点。

    【思路】

    数据结构入门算法。分别为两个链表设“滑块”,比较当前滑块数值的大小,小的就将返回链表的末尾指针指向它。

    注意:

    1.要为返回链表设立总是指向其尾部节点的标志,方便归入新节点。

    2.考虑原始链表为空的情况。

    【my code】

    写的比较笨,但总归是对的。值得鼓励。

    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
     };
    
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode *head=NULL;
        ListNode *p=NULL;
        ListNode *q=NULL;
        if(l1==NULL&&l2==NULL)
            return NULL;
        else if(l1==NULL)
            return l2;
        else if(l2==NULL)
            return l1;
        if(l1->val<l2->val){
            head=l1;
            p=l1->next;
            q=l2;
        }
        else{
            head=l2;
            p=l1;
            q=l2->next;
        }  
        ListNode *r=head;
        while(p!=NULL&&q!=NULL)
        {
            if(p->val<q->val){
                r->next=p;
                p=p->next;
                r=r->next;
            }
            else{
                r->next=q;
                q=q->next;
                r=r->next;
            }
    
        }
        if(p!=NULL)
            r->next=p;
        if(q!=NULL)
            r->next=q;
        return head;
    }

    【other code】

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            ListNode *helper=new ListNode(0);//注意这里!换成listNode *helper=NULL是不可行的
            ListNode *head=helper;
            while(l1 && l2)
            {
                 if(l1->val<l2->val) helper->next=l1,l1=l1->next;
                 else helper->next=l2,l2=l2->next;
                 helper=helper->next;
            }
            if(l1) helper->next=l1;
            if(l2) helper->next=l2;
            return head->next;
        }

    【对比评价】

    1.由于传入参数不是引用和const,实际传入的是副本,修改不会影响原来的链表。所以无需设立指针p,q,直接用l1,l2即可。

    2.排除空链情况的思路太繁琐。注意标注的地方,为helper分配了一个节点,初始化其val=0;其next默认初始化为NULL,因此l1,l2为null时,返回head->next是没问题的。

    如果hepler=null,则返回错误。这里helper充当head的尾节点指针。

    【后记】

    this is the first time that I made it all by myself in 35 minutes.

    though there is a long way to go, it's still an encouragement for me.

  • 相关阅读:
    Cannot complete this action,please try again. Correlation ID :bd640a9d-4c19-doff-2fe0-6ce1104b59ae
    我的工作流为什么启动不了
    关于IE下复选框的样式问题
    使用SharePoint rest语法返回已上传的SharePoint Excel 文件
    Running the complier from the Command Line
    关于inline
    来到坡国
    在oracle Virtual Box 虚拟机中搭建hadoop1.2.1完全分布式环境(转自康哥的博客)
    hadoop调试
    linux相关指令学习
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4413770.html
Copyright © 2020-2023  润新知