链表----两个链表相加生成相加链表

关键点:

  • 1、将链表拆成左右两部分
  • 2、合并左右两部分 
//1、将链表从中间断开,分成左右两部分
	public static Node reCombination(Node head) {
		if(head == null || head.next == null || head.next.next == null) {
			return head;
		}
		//找中点从中间断开
		Node p1 = head.next.next;
		Node p2 = head.next;
		while(p1.next != null && p1.next.next != null) {
			p1 = p1.next.next;
			p2 = p2.next;
		}//p2到达中点位置
		Node right = p2.next;//右半部分链表头
		p2.next = null;//断开
		printList(head);
		printList(right);
		return mergeList(head,right);	
	}
	
	//2、合并左右两部分
	public static Node mergeList(Node left,Node right) {
		if(left == null || right == null)  return null;
		Node head = left;
		Node nextL = null;
		Node nextR = null;
		while(left.next != null) {
			nextL = left.next;
			left.next = right;
			nextR = right.next;
			left = nextL;
			right.next = left;
			right = nextR;
		}
		if(left != null) {
			left.next = right;
		}
		
		return head;	
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值