LeetCode原题: 21. 合并两个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null || list2 == null) {
return list1 != null ? list1 : list2;
}
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
}
使用Java语言模拟,两个有序链表的合并。
public class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
'}';
}
}
public class SequentialList {
public ListNode head;
//头插法
public void addHead(ListNode newNode) {
if (head == null) {
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
//尾插法
public void addTail(ListNode newNode) {
if (head == null) {
head = newNode;
return;
}
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newNode;
}
//遍历
public void show() {
ListNode cur = head;
while (cur != null) {
System.out.println(cur);
cur = cur.next;
}
}
//递归解决两个有序链表的合并
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
/* if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}*/
if (list1 == null || list2 == null) {
return list1 != null ? list1 : list2;
}
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
public static void main(String[] args) {
SequentialList l1 = new SequentialList();
ListNode head1 = new ListNode(1);
l1.addTail(head1);
l1.addTail(new ListNode(3));
l1.addTail(new ListNode(6));
SequentialList h2 = new SequentialList();
ListNode head2=new ListNode(2);
h2.addTail(head2);
h2.addTail(new ListNode(4));
h2.addTail(new ListNode(5));
//两个链表的头节点
ListNode listNode = mergeTwoLists(head1, head2);
//返回的listNode即是合并后链表l3的头节点
SequentialList l3=new SequentialList();
l3.addHead(listNode);
l3.show();
}
}
运行结果: