Niuke.com High Frequency Algorithm Questions Series - BM11 - Linked List Addition (2)

Niuke.com High Frequency Algorithm Questions Series - BM11 - Linked List Addition (2)

Topic description

Assuming that the value of each node in the linked list is between 0 and 9, then the entire linked list can represent an integer. Given two such linked lists, generate the resulting linked list representing the sum of the two integers.

Solution 1: Use stack

First, the special case judgment:

• If linked list one is empty, return linked list two directly
• If the linked list 2 is empty, return the linked list 1 directly

Otherwise, 2 stacks are used to store the nodes of the two linked lists:

• First add the nodes in the two linked lists to the stack;
• Traverse 2 stacks, that is, perform addition, and add the value to the new stack, so that the node values can be added in reverse order, and a variable needs to be used to record the carry value;
• It should be noted that after the traversal is completed, it is necessary to judge whether additional nodes need to be added according to the carry value;
• Finally, construct the added linked list according to the new stack and return it.

If you don't want to use extra stack space, you can consider reordering the two linked lists in reverse order before performing the addition.

code

``` ```import java.util.Stack;

public class Bm011 {

/**
* 链表相加：使用栈
*
* @return ListNode类
*/
// 如果链表一为空，则直接返回链表二
}
// 如果链表二为空，则直接返回链表一
}
// 2个栈用来存放两个链表的结点
Stack<ListNode> nodes1 = new Stack<>();
Stack<ListNode> nodes2 = new Stack<>();
}
}

// 记录进位值
Stack<Integer> newNodes = new Stack<>();
// 遍历栈，即执行加法，将值添加到新的栈中
while (!nodes1.isEmpty() || !nodes2.isEmpty()) {
int val1 = 0, val2 = 0, newVal = 0;
if (!nodes1.isEmpty()) {
val1 += nodes1.pop().val;
}
if (!nodes2.isEmpty()) {
val2 += nodes2.pop().val;
}
newVal += addOne + val1 + val2;
if (newVal > 9) {
newVal = newVal % 10;
} else {
}
newNodes.push(newVal);
}
newNodes.push(1);
}
while (!newNodes.isEmpty()) {
next.next = new ListNode(newNodes.pop());
next = next.next;
}
}

public static void main(String[] args) {
// 链表一： 1 -> 3 -> 5
// 链表二： 2 -> 4 -> 6

// 测试用例，期望输出： 3 -> 8 -> 1
}
}``````
\$1.01^{365} ≈ 37.7834343329\$
\$0.99^{365} ≈ 0.02551796445\$
Believe in the power of persistence!

1.8k 声望
7.1k 粉丝
0 条评论