两个单链表生成相加链表

问题描述:假设两个链表每个节点值都在0-9之间,那么链表整体可以代表一个整数。例如:9->3>7,可以代表937,6->3,可以代表63

两个链表相加即为937+63=1000,所对应的链表即为1->0->0->0

思路:首先将两个链表逆序,这样就可以模拟从低位到高位的加法

public Node reverselist(Node head){
		Node next=null;
		Node pre=null;
		while (head!=null) {
			next=head.next;
			head.next=pre;
			//head指针往后移
			pre=head;
			head=next;	
		}
		return head;		
	}

            同步遍历两个逆序链表,在这个过程中执行加法操作,并生成一个新节点,该节点的值为两个数字相加的和值,将每次循环生成的节点相连,同时要关注两个数字相加之后有无进位,若产生进位,则执行下次加法时要加上这个进位,即n=n1+n1+ca,无进位时,ca=0

        //首先逆序两个链表
		head1=reverselist(head1);
		head2=reverselist(head2);
		Node c1=head1;
		Node c2=head2;
		int n1=0;//链表1的值
		int n2=0;//链表2的值
		int n=0;
		int ca=0;//进位
		Node pre=null;
		Node node=null;
		//循环取出链表的值执行加法,直到两个链表均为null为止
		while (c1!=null||c2!=null) {
			n1=c1!=null?c1.value:0;
			n2=c2!=null?c2.value:0;
			n=n1+n2+ca;
			//创建一个新节点,值为n%10
			//插入一个新节点,与旧节点相连
			pre=node;
			node=new Node(n%10);
			node.next=pre;
			
			ca=n/10;
			c1=c1!=null?c1.next:null;
			c2=c2!=null?c2.next:null;
	
		}

            执行完循环加法之后,观察此时进位是否为1,若还有进位,则需要将1也链接到最后生成的链表上

if (ca==1) {
	pre=node;
	node=new Node(1);
	node.next=pre;			
}

整体代码:

public class Node{
		public int value;
		public Node next;
		public Node(int value) {
			this.value=value;			
		}
	}
public Node reverselist(Node head){
		Node next=null;
		Node pre=null;
		while (head!=null) {
			next=head.next;
			head.next=pre;
			//head指针往后移
			pre=head;
			head=next;	
		}
		return head;		
	}
public Node add_list(Node head1,Node head2){
		//首先逆序两个链表
		head1=reverselist(head1);
		head2=reverselist(head2);
		Node c1=head1;
		Node c2=head2;
		int n1=0;//链表1的值
		int n2=0;//链表2的值
		int n=0;
		int ca=0;//进位
		Node pre=null;
		Node node=null;
		//循环取出链表的值执行加法,直到两个链表均为null为止
		while (c1!=null||c2!=null) {
			n1=c1!=null?c1.value:0;
			n2=c2!=null?c2.value:0;
			n=n1+n2+ca;
			//创建一个新节点,值为n%10
			//插入一个新节点
			pre=node;
			node=new Node(n%10);
			node.next=pre;
			
			ca=n/10;
			c1=c1!=null?c1.next:null;
			c2=c2!=null?c2.next:null;
	
		}
		//循环相加结束之后,判断进位还是否为1,若为1则还需要链接一个值为1的节点
		if (ca==1) {
			pre=node;
			node=new Node(1);
			node.next=pre;			
		}
		//最后将两个链表还原并返回要求链表的头节点
		reverselist(head1);
		reverselist(head2);		
		return node;		
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值