[算法]合并两个有序的单链表

一世执手 提交于 2020-03-03 22:54:41

题目:

给定两个有序单链表的头结点head1和head2.请合并两个有序链表,合并后的链表依然有序,并返回合并后的链表的头结点。

例如:

0->2->3->7->null;

1->3->5->7->9->null;

合并后的链表为:0->1->2->3->3->5->7->7->9->null。

程序:

public static Node merge(Node head1,Node head2){
		if (head1==null||head2==null) {
			return head1=head2==null?head2:head1;
		}
		Node head=head1.value<head2.value?head1:head2;
		Node cur1=head1.value<head2.value?head1:head2;
		Node cur2=head1.value>head2.value?head1:head2;
		Node pre=cur1;
		Node next=cur1.next;
		while(cur1!=null&&cur2!=null){
			if (cur1.value<=cur2.value) {
				pre=cur1;
				cur1=cur1.next;
			}else{
				next=cur2.next;
				pre.next=cur2;
				cur2.next=cur1;
				pre=cur2;
				cur2=next;
			}
		}
		pre.next=cur1==null?cur2:cur1;
		return head;
	}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!