Leecode刷题之旅-C语言/python-21.合并两个有序链表

/*
 * @lc app=leetcode.cn id=21 lang=c
 *
 * [21] 合并两个有序链表
 *
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
 *
 * algorithms
 * Easy (52.72%)
 * Total Accepted:    47.1K
 * Total Submissions: 89K
 * Testcase Example:  '[1,2,4]
[1,3,4]'
 *
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
 * 
 * 示例:
 * 
 * 输入:1->2->4, 1->3->4
 * 输出:1->1->2->3->4->4
 * 
 * 
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
 
  struct ListNode* newNode;   
  if(!l1)        
  return l2;    
  if(!l2)        
  return l1;    
  if(l1->val<l2->val)    
  {       
  newNode=l1;        
  newNode->next=mergeTwoLists(l1->next,l2);    
  }    
  else    
  {        
      newNode=l2;        
      newNode->next=mergeTwoLists(l1,l2->next);    
  }    
     
      return newNode;
}

这里用递归的方法进行合并。在第一次的判断中, 如果l1的值小于l2的值,新的结点从l1开始,然后下一个结点 继续是 l1的下一个值和l2进行该函数比较,反之则从l2开始。

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

python:

#
# @lc app=leetcode.cn id=21 lang=python3
#
# [21] 合并两个有序链表
#
# https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
#
# algorithms
# Easy (52.72%)
# Total Accepted:    47.1K
# Total Submissions: 89K
# Testcase Example:  '[1,2,4]
[1,3,4]'
#
# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
# 
# 示例:
# 
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# 
# 
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1==None and l2==None:
            return None
        if l1==None:
            return l2
        if l2==None:
            return l1
        if l1.val<=l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2
原文地址:https://www.cnblogs.com/lixiaoyao123/p/10492205.html