原文連接:wangwei.one/posts/java-…html
前面,咱們實現了鏈表的 環檢測 操做,本篇來聊聊,如何合併兩個有序鏈表。java
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
複製代碼
定義一個臨時虛假的Head節點,再建立一個指向tail的指針,以便於在尾部添加節點。post
對ListNode1和ListNode2同時進行遍歷,比較每次取出來的節點大小,並綁定到前面tail指針上去,直到最終全部的元素所有遍歷完。spa
最後,返回 dummyNode.next
,即爲新鏈表的head節點。3d
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(0);
ListNode tail = dummyNode;
while(true){
if(l1 == null){
tail.next = l2;
break;
}
if(l2 == null){
tail.next = l1;
break;
}
ListNode next1 = l1;
ListNode next2 = l2;
if(next1.val <= next2.val){
tail.next = next1;
l1 = l1.next;
}else{
tail.next = next2;
l2 = l2.next;
}
tail = tail.next;
}
return dummyNode.next;
}
}
複製代碼
使用遞歸的方式,代碼比遍歷看上去簡潔不少,可是它所佔用的棧空間會隨着鏈表節點數量的增長而增長。指針
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = null;
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val <= l2.val){
result = l1;
result.next = mergeTwoLists(l1.next, l2);
}else{
result = l2;
result.next = mergeTwoLists(l1, l2.next);
}
return result;
}
}
複製代碼