两个链表合并不加入新的链表空间

class LNode {
	int value;
	LNode next;

	public LNode(int value, LNode next) {
		this.value = value;
		this.next = next;
	}

}

public class MergeTowList {

	public static void main(String[] args) {
		LNode A5 = new LNode(21, null);
		LNode A4 = new LNode(13, A5);
		LNode A3 = new LNode(10, A4);
		LNode A2 = new LNode(6, A3);
		LNode A1 = new LNode(3, A2);

		LNode B4 = new LNode(14, null);
		LNode B3 = new LNode(12, B4);
		LNode B2 = new LNode(6, B3);
		LNode B1 = new LNode(4, B2);

		LNode merge = mergeLinks(A1, B1);
		System.out.println(123123);
		while (merge != null) {
			if (merge.next != null) {
				System.out.print(merge.value + ",");
			} else {
				System.out.print(merge.value);
			}

			merge = merge.next;
		}

	}

	public static LNode mergeLinks(LNode head1,LNode head2){
		if(head1==null){
			return head2;
		}
		if(head2==null){
			return head1;
		}
		LNode head;
		if(head1.value>head2.value){
			head = head2;
			head2=head2.next;
		}else{
			head = head1;
			head1=head1.next;
		}
		LNode current=head;//current指向新的链表的最后一个节点
		while(head1!=null && head2!=null){
			if(head1.value>head2.value){
				current.next=head2;
				current=head2;
				head2=head2.next;
			}else{
				current.next=head1;
				current = head1;
				head1=head1.next;
			}
		}
		if(head1!=null){//把listA的全部插入到current后面
			current.next=head1;
		}
		if(head2!=null){
			current.next=head2;
		}
		
		return head;
		
	}

}

 

posted @ 2016-11-20 00:49  鹏鹏进阶  阅读(484)  评论(0编辑  收藏  举报