mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 19:13:42 +00:00
Update 25. 合并两个排序的链表.md
补充递归与迭代解法的思路说明。
This commit is contained in:
@@ -10,6 +10,8 @@
|
||||
|
||||
### 递归
|
||||
|
||||
比较两个链表的头节点,较小的那个作为合并结果的头节点,它的 next 指向剩余部分合并的结果,剩余部分的合并是同一个问题。
|
||||
|
||||
```java
|
||||
public ListNode trainningPlan(ListNode l1, ListNode l2) {
|
||||
if (l1 == null)
|
||||
@@ -28,6 +30,8 @@ public ListNode trainningPlan(ListNode l1, ListNode l2) {
|
||||
|
||||
### 迭代
|
||||
|
||||
用一个不存值的头结点 head 简化边界处理,cur 指向合并结果的末尾。每次把两个链表中较小的头节点接到 cur 后面,一个链表用完后,把另一个链表剩下的部分整个接上。
|
||||
|
||||
```java
|
||||
public ListNode trainningPlan(ListNode l1, ListNode l2) {
|
||||
ListNode head = new ListNode(-1);
|
||||
|
||||
Reference in New Issue
Block a user