链表求和

leetCode:

https://leetcode.com/problems/add-two-numbers-ii/description/

 

描述:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7


这题最容易想到的思路就是将链表反转,然后同时遍历两个链表,最后再将加和后的链表反转回来。
但是题目最后提高了难度,如果原链表不能改变,也就是不能反转链表,该如何解决呢??

答案就是使用栈,遍历链表依次将元素压入栈中,元素的顺序就被反转过来了,低位的数字在栈上面,高位的数字在栈底部。
循环第从两个栈顶弹出元素,执行加法逻辑,并将相加后的元素放入一个新的栈中,这样求和结果中低位数字在栈底,高位数字在栈顶,

最后循环从栈顶弹出元素,构建节点之间的指向关系,形成从高位到低位的链表。

代码:

public class AddTwoNumbers {

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = pushToStck(l1);
Stack<Integer> stack2 = pushToStck(l2);
Stack<ListNode> result = new Stack<>();
int carry = 0;
while (true) {
if (stack1.isEmpty() && stack2.isEmpty()) {
break;
}
int s1 = stack1.isEmpty() ? 0 : stack1.pop();
int s2 = stack2.isEmpty() ? 0 : stack2.pop();
result.push(new ListNode((s1 + s2 + carry) % 10));
carry = (s1 + s2 + carry) / 10;
}
if (carry != 0) {
result.push(new ListNode(1));
}
ListNode newHead = null, newTail = null;
while (!result.isEmpty()) {
if (newHead == null) {
newHead = newTail = result.pop();
} else {
newTail.next = result.pop();
newTail = newTail.next;
}
}
return newHead;
}

public Stack<Integer> pushToStck(ListNode l) {
Stack<Integer> stack = new Stack<>();
while (l != null) {
stack.push(Integer.valueOf(l.val));
l=l.next;
}
return stack;
}
}

posted on 2019-05-26 17:54  _朱葛  阅读(558)  评论(0编辑  收藏  举报