0
点赞
收藏
分享

微信扫一扫

LeetCode Top 100 Liked Questions 21. Merge Two Sorted Lists (Java版; Easy)


​​welcome to my blog​​

LeetCode Top 100 Liked Questions 21. Merge Two Sorted Lists (Java版; Easy)

题目描述

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

第一次做, 创建临时头结点, 不用分别处理头结点和非头结点; 模拟归并排序的归并过程, 注意不同之处:需要保存上一个节点; while后面是if, 不再是while了; 代码中某四行可以用一行代替 curr.next = left!=? left : right;

/*
创建tempHead, 就不用将头结点和非头结点分开处理了
模拟归并排序的归并过程
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;

ListNode tempHead = new ListNode(0);
ListNode left=l1, right=l2, curr=tempHead;
while(left!=null && right!=null){
if(left.val < right.val){
curr.next = left;
left = left.next;
}
else{
curr.next = right;
right = right.next;
}
curr = curr.next;
}
/*
下面四行可以用一行代替
curr.next = left!=? left : right;
*/
//这里不是while, 是if!!!
if(left!=null)
curr.next = left;
if(right!=null)
curr.next = right;
return tempHead.next;
}
}

第一次做, 递归版

/*
递归版
递归函数逻辑:找出两个链表中可以作为头结点的节点, 该头结点连接其余部分的头结点
返回值:当前头结点
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//base case
if(l1==null)
return l2;
if(l2==null)
return l1;
//
ListNode head=null;
if(l1.val<l2.val){
head = new ListNode(l1.val);
head.next = mergeTwoLists(l1.next, l2);
}

else{
head = new ListNode(l2.val);
head.next = mergeTwoLists(l1, l2.next);
}
return head;
}
}


举报

相关推荐

0 条评论