描述:
已知两个链表head1和head2各自有序,请把它们合并成一个依然有序的链表。结果链表要包含head1和head2的所有结点,即结点值相同。
方法1:递归法
具体步骤如下所示:
1)比较链表1(head1)和链表2(head2)的第一个结点数据,如果head1.data<head2.data,则把结果链表头结点指向链表head1中的第一个结点。
2)对剩余的链表head1.next和链表2(head2)再调用同样的方法,比较得到结果链表的第二个结点,添加到合并后列表的后面。
3)一直递归调用步骤2),直到两个链表的结点都被加到结果链表中。
代码如下:
class Node{
Node next=null;
int data;
public Node(int data){
this.data=data;
}
}
public class Test {
public static Node mergeList(Node head1,Node head2){
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
Node head=null;
if(head1.data<head2.data){
head=head1;
head.next=mergeList(head1.next,head2);
}
else{
head=head2;
head.next=mergeList(head1,head2.next);
}
return head;
}
public static void main(String[] args) {
Node head1=new Node(1);
Node node3=new Node(3);
head1.next=node3;
Node node5=new Node(5);
node3.next=node5;
node5.next=null;
Node head2=new Node(2);
Node node4=new Node(4);
head2.next=node4;
Node node6=new Node(6);
node4.next=node6;
node6.next=null;
Node mergeHead=mergeList(head1,head2);
while(mergeHead!=null){
System.out.print(mergeHead.data+" ");
mergeHead=mergeHead.next;
}
}
}
方法二:非递归法
在遍历两个链表过程中,改变当前链表指针的指向来把两个链表串连成一个有序的列表,实现代码如下:
public class Test2 {
public static Node mergeList(Node head1,Node head2){
if(head1==null)
return head2;
if(head2==null)
return head1;Node p1,p2,head;
//确定合并后的头节点
if(head1.data<head2.data){
head=head1;
p1=head1.next;
p2=head2;
}
else{
head=head2;
p1=head1;
p2=head2.next;
}
Node pcur=head;
while(p1!=null&&p2!=null){
//把链表head1当前遍历的结点添加到合并后链表的尾部
if(p1.data<=p2.data){
pcur.next=p1;
pcur=p1;
p1=p1.next;
}
//把链表head2当前遍历的节点添加到合并后链表尾部
else{
pcur.next=p2;
pcur=p2;
p2=p2.next;
}
//head2链表已经遍历结束,把head1遍历剩余的结点添加到合并后链表的尾部
if(p1!=null){
pcur.next=p1;
}
if(p2!=null){
pcur.next=p2;
}
}
return head;
}
}