LeetCode21. 合并两个有序链表(Java)
题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
代码:
- 解法一l
/**
* 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 p1=l1;
ListNode p2=l2;
ListNode root=new ListNode(0);
ListNode rear=root;
while(true){
if(p1==null&&p2==null){
break;
}else if(p1!=null&&p2==null){
rear.next=p1;
rear=p1;
break;
}else if(p1==null&&p2!=null){
rear.next=p2;
rear=p2;
break;
}else if(p1.val>=p2.val){
rear.next=p2;
rear=p2;
p2=p2.next;
rear.next=null;
}else{
rear.next=p1;
rear=p1;
p1=p1.next;
rear.next=null;
}
}
return root.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) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = null;
if (l1.val <= l2.val){
head = l1;
head.next = mergeTwoLists(l1.next, l2);
} else {
head = l2;
head.next = mergeTwoLists(l1, l2.next);
}
return head;
}
}