zoukankan      html  css  js  c++  java
  • leetcode 21.合并两个有序链表(迭代)

    1.题目链接

    https://leetcode-cn.com/problems/merge-two-sorted-lists/

    2.题目描述

      将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    示例:
    
    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    3.题目解析

      用迭代方法求解,当l1或者l2为空时,则返回另一个链表;否则, l1 l2 都不是空链表,判断 l1 l2 哪一个链表的头节点的值更小,将较小值的节点添加到结果里,对应链表中的节点向后移一位。

    4.代码实现

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
     9     if (l1 == NULL) {
    10         return l2;
    11 }
    12     if (l2 == NULL) {
    13         return l1;
    14 }
    15     if (l1->val < l2->val) {
    16         l1->next = mergeTwoLists(l1->next, l2);
    17         return l1;
    18     }
    19     else {
    20         l2->next = mergeTwoLists(l1, l2->next);
    21         return l2;
    22     }
    23 }

    5.提交记录

    stay hungry, stay foolish
  • 相关阅读:
    状压DP
    string
    hdu3068
    HDU Stealing Harry Potter's Precious(状压BFS)
    状压BFS
    BFS+打印路径
    poj Meteor Shower
    C语言-无符号数与有符号数不为人知的秘密
    keras_实现cnn_手写数字识别
    python_plot画图参数设置
  • 原文地址:https://www.cnblogs.com/zygote/p/12812806.html
Copyright © 2011-2022 走看看