题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here Stack<ListNode> Stack1 = new Stack<>(); Stack<ListNode> Stack2 = new Stack<>(); while (head1 != null) { Stack1.add(head1); head1 = head1.next; } while (head2 != null) { Stack2.add(head2); head2 = head2.next; } System.out.println(Stack1.size()); System.out.println(Stack2.size()); Stack<ListNode> sc = (Stack1.size() > Stack2.size()) ? Stack1 : Stack2; System.out.println("sc" + sc.size()); int i = 0; int size = sc.size(); Stack<ListNode> datas = new Stack<>(); for(int z = 0;z<size;z++ ) { int s1 = Stack1.isEmpty() ? 0 : Stack1.pop().val; int s2 = Stack2.isEmpty() ? 0 : Stack2.pop().val; int sum = s1 + s2 + i; System.out.println("sum" + sum); if (sum > 9) { i = 1; datas.add(new ListNode(sum%10)); } else { i = 0; datas.add(new ListNode(sum)); } } if(i == 1){ datas.add(new ListNode(i)); } System.out.println("datas" + datas.size()); ListNode result = datas.pop(); ListNode temp = result; while (!datas.isEmpty()) { ListNode pop = datas.pop(); temp.next = pop; temp = temp.next; } return result; } } 思路:应用栈,先进后出,遍历放入进去,计算的时候,根据栈弹出两个值计算,通过一个全局变量记录进位,大于9取模,计算累加数据放入栈中,最后遍历弹出栈数据,组装链表 第一个题目没有看资料,自己弄出来的,虽然写的代码不好,很开心,慢慢进步