合并两个有序链表(简单)
2020年4月19日
题目来源:合并两个有序链表
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解题思路
迭代法:每次判断小值,直到一个链表为空;把另一个链表直接加入。重点是虚拟头节点指明这个链表的头部,再用一个节点去指定下一个节点。
递归法:递归找小值
代码实现
迭代法
/**
* 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 phead=new ListNode(0); //虚拟头节点
ListNode head=phead; //记录每次next的前一个节点
while(l1!=null && l2!=null){ //如果都不为空的话,判断小值,连接小值
if(l1.val<l2.val){
head.next=l1;
l1=l1.next;
}else{
head.next=l2;
l2=l2.next;
}
head=head.next;
}
//一个为空就说明另外一个都比它大,直接连接它的所有节点
if(l1!=null) head.next=l1;
if(l2!=null) head.next=l2;
return phead.next;
}
}
递归法
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
else if (l2 == null) {
return l1;
}
else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}