我是靠谱客的博主 精明乌冬面,最近开发中收集的这篇文章主要介绍java 链表两数相加1.题目一2.题目二,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

目录

  • 1.题目一
  • 2.题目二

1.题目一

给定两个用链表表示的整数,每个节点包含一个数位。

这些数位是反向存放的,也就是个位排在链表首部。

编写函数对这两个整数求和,并用链表形式返回结果
两数相加
反向存放:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;//表示进位
ListNode head = null, tail = null;
while (l1 != null || l2 != null) {
//如果其中有一个到达结尾了,那么这个链表这一位的的数字就为0。
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
if (head == null) {//第一次插入
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry == 1) tail.next = new ListNode(carry);
return head;
}

2.题目二

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

两数相加 II
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]

难点在于链表中数位的顺序与我们做加法的顺序是相反的,为了逆序处理所有数位,我们可以使用栈:把所有数字压入栈中,再依次取出相加。计算过程中需要注意进位的情况。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode newHead = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
int x = stack1.isEmpty() ? 0 : stack1.pop();
int y = stack2.isEmpty() ? 0 : stack2.pop();
int cur = x + y + carry;
carry = cur / 10;//进位
cur %= 10;
ListNode curnode = new ListNode(cur);//创建结点
curnode.next = newHead;
newHead = curnode;
}
return newHead;
}

最后

以上就是精明乌冬面为你收集整理的java 链表两数相加1.题目一2.题目二的全部内容,希望文章能够帮你解决java 链表两数相加1.题目一2.题目二所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部