• Merge Two Sorted Lists


    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            //维护一个新的链表,分别用两个指针指向链表,应当注意头结点和后面的节点操作不一样
            if(l1==NULL)
            return l2;
            if(l2==NULL)
            return l1;
            ListNode*head= NULL;//头指针
            ListNode*cur= NULL;//当前操作的点
            ListNode*p =l1;
            ListNode*q =l2;
          
            while(p&&q)
            {if (head == NULL)
               {if (p->val<q->val)
                  {
                  head = cur= p;
                  p= p->next;
                  head->next = NULL;
                  }
                 
                else
                {
                  head = cur = q;
                  q= q->next;
                  head->next = NULL;
                   
                }
               }
           
            else
            {
              if (p->val<q->val)
                  {
                  cur->next= p;
                  cur= cur->next ;
                  p= p->next;
                  cur->next = NULL;
                  } 
             else
               {
                cur->next= q;
                cur= cur->next ;
                q= q->next;
                cur->next = NULL;
               }
            }
        }
           
        if(p!= NULL)
        cur->next= p;
        else if(q!= NULL)
        cur->next = q;
        return head;
        }
    };

  • 相关阅读:
    Linux进程管理及while循环(转)
    AT5661-[AGC040C]Neither AB nor BA【模型转换】
    CF573D-Bear and Cavalry【动态dp】
    关于专人整理和分析需求
    Codeforces 1005D Polycarp and Div 3
    [Luogu]P5513 [CEOI2013]Board
    IDEA Mybatis 中文数据添加到MySQL,显示乱码
    如何比较两个word文档的差异
    抗体计算设计
    抗体
  • 原文地址:https://www.cnblogs.com/gofighting/p/5036213.html
Copyright © 2020-2023  润新知