Merge Two Sorted Lists
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.
两个单链表的合并
package leetcode;
public class leet21 {
private static class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int x){ val = x;}
}
public static void main(String[] args) {
ListNode l0 = new leet21.ListNode();
ListNode l1 = new leet21.ListNode(1);
ListNode l2 = new leet21.ListNode(2);
ListNode l3 = new leet21.ListNode(5);
l0.next = l1;
l1.next = l2;
l2.next = l3;
ListNode h0 = new leet21.ListNode();
ListNode h1 = new leet21.ListNode(3);
ListNode h2 = new leet21.ListNode(4);
ListNode h3 = new leet21.ListNode(6);
h0.next = h1;
h1.next = h2;
h2.next = h3;
leet21 leet = new leet21();
ListNode node = leet.mergeTwoList(l0, h0);
while(node != null){
System.out.println(node.val);
node = node.next;
}
}
public ListNode mergeTwoList(ListNode l1,ListNode l2){
ListNode head = l1;
ListNode p = l1;
l1 = l1.next;
l2 = l2.next;
while(l1 != null && l2 !=null){
if(l1.val < l2.val){
p.next = l1;
p = l1;
l1 = l1.next;
}else{
p.next = l2;
p = l2;
l2 = l2.next;
}
}
if(l1 == null)p.next = l2;
if(l2 == null)p.next = l1;
return head;
}
}
本文介绍了一种将两个已排序的单链表合并为一个新的排序链表的方法。通过比较两个链表节点的值来决定合并顺序,最终形成一个新的有序链表。文章提供了完整的Java实现代码,并展示了如何创建链表及合并后的输出。

4746

被折叠的 条评论
为什么被折叠?



