两种方法实现:
1.递归
2.非递归
public class MergeList {
public static void main(String[] args){
Node p1=new Node(2);
Node p2=new Node(3);
Node p3=new Node(5);
Node p4=new Node(9);
p1.next=p2;
p2.next=p3;
p3.next=p4;
Node q1=new Node(2);
Node q2=new Node(4);
Node q3=new Node(6);
Node q4=new Node(7);
Node q5=new Node(8);
q1.next=q2;
q2.next=q3;
q3.next=q4;
q4.next=q5;
//Node n=new MergeList().merge(p1,q1);
Node n=new MergeList().merge2(p1,q1);
while(n!=null){
System.out.print(n.data+" ");
n=n.next;
}
}
public Node merge(Node h1,Node h2){
//首先,判断是否有链表为空
if(h1==null)
return h2;
if(h2==null)
return h1;
Node h0=null;
//比较
if(h1.data<h2.data) {
h0 = h1;
h0.next = merge(h1.next, h2);
}else{
h0=h2;
h0.next = merge(h1,h2.next);
}
return h0;
}
public Node merge2(Node h1,Node h2) {
if (h1 == null) {
return h2;
}
if (h2 == null) {
return h1;
}
//确定头指针
Node tailNode = null;//指向新链表最后一个结点
Node head = null;//指向合并后链表第一个结点
if (h1.data <= h2.data) {
head = h1;
h1 = h1.next;//指向第二个结点
} else {
head = h2;
h2 = h2.next;
}
tailNode = head;//指向第一个结点
while (h1 != null && h2 != null) {
if (h1.data <= h2.data) {
tailNode.next = h1;
h1 = h1.next;
} else {
tailNode.next = h2;
h2 = h2.next;
}
tailNode = tailNode.next;//后移
}
//剩余结点的处理
if (h1==null) {
tailNode.next = h2;
} else if (h2==null) {
tailNode.next = h1;
}
return head;
}
}