zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】Merge Two Sorted Lists .

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    解题:

    题目比较简单,注意由于表头不确定,因此新建一个结点指向新创建的链表;

    解题步骤:

    1、判断l1和l2是否有效

    2、新建preHead结点,newlist指针指向preHead;

    3、循环开始,满足l1和l2都不为空:

      (1)比较当前l1和l2的值,将较小的穿进newlist中

    4、newlist链接l1或l2的剩余部分

    5、释放表头,返回newlist;

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    12         if (l1 == NULL) return l2;
    13         if (l2 == NULL) return l1;
    14         
    15         ListNode* prehead = new ListNode(0);
    16         ListNode* newlist = prehead;
    17         
    18         while (l1 != NULL && l2 != NULL) {
    19             if (l1->val > l2->val) {
    20                 newlist->next = l2;
    21                 l2 = l2->next;
    22             } else {
    23                 newlist->next = l1;
    24                 l1 = l1->next;
    25             }
    26             newlist = newlist->next;
    27         }
    28         
    29         if (l1 == NULL) newlist->next = l2;
    30         else newlist->next = l1;
    31         
    32         l1 = prehead->next;
    33         delete prehead;
    34         return l1;
    35     }
    36 };
  • 相关阅读:
    面向对象编程的三大特征: 封装、继承、多态
    CDH和HDP对比
    mapreduce、spark、tez区别
    minio原理和使用
    HDP、CDH、CDP升级
    常用的分布式文件系统
    linux平台下防火墙iptables原理(转)
    php 1207
    php 1209
    php 1130
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4587514.html
Copyright © 2011-2022 走看看