头图

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.

See the original title: BM11 linked list addition (2)

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 {

    /**
     * 链表相加:使用栈
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public static ListNode addInList(ListNode head1, ListNode head2) {
        // 如果链表一为空,则直接返回链表二
        if (head1 == null) {
            return head2;
        }
        // 如果链表二为空,则直接返回链表一
        if (head2 == null) {
            return head1;
        }
        // 2个栈用来存放两个链表的结点
        Stack<ListNode> nodes1 = new Stack<>();
        Stack<ListNode> nodes2 = new Stack<>();
        while (head1 != null) {
            nodes1.push(head1);
            head1 = head1.next;
        }
        while (head2 != null) {
            nodes2.push(head2);
            head2 = head2.next;
        }

        // 记录进位值
        int addOne = 0;
        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;
                addOne = 1;
            } else {
                addOne = 0;
            }
            newNodes.push(newVal);
        }
        if (addOne == 1) {
            newNodes.push(1);
        }
        ListNode newHead = new ListNode(-1);
        ListNode next = newHead;
        while (!newNodes.isEmpty()) {
            next.next = new ListNode(newNodes.pop());
            next = next.next;
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        // 链表一: 1 -> 3 -> 5
        ListNode head1 = ListNode.testCase3();
        // 链表二: 2 -> 4 -> 6
        ListNode head2 = ListNode.testCase4();

        // 测试用例,期望输出: 3 -> 8 -> 1
        ListNode.print(addInList(head1, head2));
    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!