java将两个有序链表合并成有序链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangquan2015/article/details/82818614

利用递归法将两有序链表合并成链表,且合并后的链表仍然有序。

  1. 比较链表1和链表2的第一个结点数据,如果head1.data<head2.data,则把结果链表头指向链表1的第一个结点。
  2. 对剩余的head1.next和链表2再次递归调用同样的方法,合并结果。
  3. 一直递归到所有结点都被加到结果链表中。
class Node{
	Node next=null;
	int data;
	public Node(int data) {
		this.data=data;
	}
}
class HelloWorld{
	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);//1->3->5
		Node node3=new Node(3);
		head1.next=node3;
		Node node5=new Node(5);
		node3.next=node5;
		node5.next=null;
		
		Node head2=new Node(2);//2->4->6
		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;//1->2->3->4->5->6
		}
	}
}

运行结果为:

1 2 3 4 5 6 

猜你喜欢

转载自blog.csdn.net/zhangquan2015/article/details/82818614