码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-11-20 06:53:51      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:lis   public   int   highlight   static   string   合并   amp   return   

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;
		
	}

}

 

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

标签:lis   public   int   highlight   static   string   合并   amp   return   

原文地址:http://www.cnblogs.com/chengpeng15/p/6081976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!