两个单链表生成相加链表

【题目】假设链表中每一个节点的值都在0~9之间,那么链表整体就可以代表一个整数。

例如:9->3->7,可以代表整数937.

给定两个两个这种链表的头结点head1和head2,请生成代表两个整数相加值的结果链表。

例如:链表1为9->3->7,链表2为6->3,最后生成新的结果链表为1->0->0->0。

public class TwoLinkedlistAdd {
	public static class Node {
		public int value;
		public Node next;

		public Node(int value) {
			this.value = value;
		}
	}

	public static Node twoLinkedListAdd(Node head1, Node head2) {
		head1 = reverse(head1);
		head2 = reverse(head2);
		int ca = 0;
		Node c1 = head1;
		Node c2 = head2;
		int n1 = 0;
		int n2 = 0;
		int n = 0;
		Node node = null;
		Node pre = null;
		while (c1 != null || c2 != null) {
			n1 = c1 == null ? 0 : c1.value;
			n2 = c2 == null ? 0 : c2.value;
			n = n1 + n2 + ca;
			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;
		}
		if (ca == 1) {
			pre = node;
			node = new Node(1);
			node.next = pre;
		}
		reverse(head1);
		reverse(head2);
		return node;
	}

	public static Node reverse(Node head) {
		Node pre = null;
		Node next = null;
		while (head != null) {
			next = head.next;
			head.next = pre;
			pre = next;
			head = next;
		}
		return head;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值