首页 > 其他 > 详细

链表求和

时间:2019-05-26 19:36:48      阅读:147      评论:0      收藏:0      [点我收藏+]

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;
}
}

链表求和

原文:https://www.cnblogs.com/zhuge134/p/10926822.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!