190505打卡:两个单链表生成相加链表

题目描述:
假设链表中每一个节点的值都在0~9之间,那么链表整体就可以代表一个整数。
例如:9->3->7,既可以代表整数937。
给定两个这种链表的头结点head1和head2,请生成代表两个整数相加值的结果链表。
例如:链表1为9->3->7,链表2为6->3,最后生成新的结果链表为1->0->0->0。

思路:将两个链表分别反转,同步遍历两个链表,将两个链表的值相加,注意在相加过程中产生的进位信息,当遍历完两个链表以后,要判断进位信息是否为1,如果为1还要生成一个值为1的节点,最后在将两个链表反转,和最原始的链表结构一样

public class Code_017_AddList {
	
	public static class Node {
		public int data;
		public Node next;
		
		public Node(int data) {
			this.data = data;
		}
	}
	
	public static Node addList(Node head1, Node head2) {
		if (head1 == null || head2 == null) {
			return head1 != null ? head1 : head2;
		}
		
		//反转链表head1
		head1 = reverseList(head1);
		
		//反转链表head2
		head2 = reverseList(head2);
		
		int carryBit = 0;//存储进位信息
		int val = 0;
		int n1 = 0;
		int n2 = 0;
		Node cur1 = head1;
		Node cur2 = head2;
		Node next = null;
		Node cur = null;
		while(cur1 != null || cur2 != null) {
			n1 = cur1 == null ? 0 : cur1.data;
			n2 = cur2 == null ? 0 : cur2.data;
//			下面这种写法是错误的,虽然在下面前两行语句中给cur1.data或cur2.data成功赋值0,但是到第三行
//			执行的时候,还是会去执行cur1.data或cur2.data,这时就会出现空指针异常
//			cur1.data = cur1 == null ? 0 : cur1.data;
//			cur2.data = cur2 == null ? 0 : cur2.data;
//			val = cur1.data + cur2.data + carryBit;
			val = n1 + n2 + carryBit;
			cur = new Node(val % 10);
			cur.next = next;
			carryBit = val / 10;
			next = cur;
			cur1 = cur1 == null ? null : cur1.next;
			cur2 = cur2 == null ? null : cur2.next;
		}
		if (carryBit == 1) {
			cur = new Node(1);
			cur.next = next;
			next = cur;
		}
		
		reverseList(head1);
		reverseList(head2);
		return cur;
	}
	
	public static Node reverseList(Node head) {
		Node prev = null;
		Node next = null;
		while(head != null) {
			next = head.next;
			head.next = prev;
			prev = head;
			head = next;
		}
		
		return prev;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值