leetcode第21题——*Merge Two Sorted Lists
来源:互联网 发布:淘宝店上传宝贝教程 编辑:程序博客网 时间:2024/06/07 21:06
题目
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.
思路
把两个有序链表归并成一个有序链表。先用比较笨但很简洁的办法:遍历两个有序链表的节点,比较节点值的大小,将较小值放入目标链表中,遍历完后如果两个链表有剩余节点,由于已经是有序的,插入目标链表的最后那个节点即可。
代码
Python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = ListNode(0) cur = head while(l1 != None and l2 != None): #遍历l1和l2的节点并比较大小,将小的放入目标链表中,cur为游标 if(l1.val < l2.val): cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur.next.next = None cur = cur.next #比较完l1和l2后还有剩余节点 if(l1 != None): cur.next = l1 else: cur.next = l2 return head.next
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head= new ListNode(0);ListNode cur = head;//遍历l1和l2的节点并比较大小,cur代表当前节点while(l1 != null && l2 != null) {if(l1.val < l2.val) {cur.next = l1;l1 = l1.next;}else {cur.next = l2;l2 = l2.next;}cur.next.next = null;//可减少链表大小,提高效率cur = cur.next;}//比较完l1和l2的节点后还有剩余节点if(l1 != null) cur.next = l1;else cur.next = l2;return head.next; }}
1 0
- leetcode第21题——*Merge Two Sorted Lists
- 【LeetCode】LeetCode——第21题:Merge Two Sorted Lists
- leetcode第21题-Merge Two Sorted Lists
- LeetCode 第 21 题 (Merge Two Sorted Lists)
- leetcode 第21题<Merge Two Sorted Lists>(java)
- 第21题:Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- LeetCode——Merge Two Sorted Lists
- LeetCode—Merge Two Sorted Lists
- leetcode——21——Merge Two Sorted Lists
- Leetcode Problem.21—Merge Two Sorted Lists
- leetcode刷题日记——Merge Two Sorted Lists
- LeetCode算法题——21. Merge Two Sorted Lists
- <21>—— Merge Two Sorted Lists
- leetcode第23题——***Merge k Sorted Lists
- LeetCode(21)Merge Two Sorted Lists
- UVA 1585 Score(模拟)
- QT Json解析方法
- (C++)二叉树中的那些常见的面试题
- Android Studio 运行 Gradle Build Running卡死的解决办法
- C# 反射详解
- leetcode第21题——*Merge Two Sorted Lists
- 通俗讲解:缓存、缓存算法和缓存框架
- Java中Iterable和Iterator的区别
- LeetCode题解:Binary Tree Level Order Traversal
- python日记——使用django心得
- 不使用第三个变量交换两个变量的值
- 虚拟机Ubuntu和Xshell 5连接
- LeetCode:319. Bulb Switcher(C版本)
- 【latex】如何解决投稿时页数不够的问题