今天是 LeetCode 算法的 第 1 阶段第 3 天 ,这一阶段主要学习链表相关的算法题和链表数据结构。今天的题目是合并两个有序的链表。
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. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
分析
合并两个「有序」列表,要求结果也有序。依次遍历两个链表,把两个链表中所有节点按大小顺序重组即可。你可以把这道题想象成两个已经按编号大小拼接好水管,把这两个水管重组,还按编号拼接到一起,简单吧!
代码
遍历单链表 L1 和 L2 ,创建一个指向结果的头指针 head,p 指向当前节点。C++ 实现如下:
结果
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists. Memory Usage: 9 MB, less than 99.71% of C++ online submissions for Merge Two Sorted Lists.
总结
整个算法思想如下:
1. 定义一个最终的链表,头指向L1和L2中头最小的那个; 2.设置一个指向最终的链表的最后一个节点指针 p,遍历L1和L2,逐步移动 p、L1、L2 的位置,直到 L1或L2中有一个为空; 3.如果L1或L2中有某一个不为空,直接插入到 p 的 next 后。
文中涉及到的算法代码,我在GitHub创建了一个项目 LeetCodeGraphically,点击阅读原文即可查看。
下一道题目留给你思考:
2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
LeetCode