链表相加问题(cont)

题目:Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

Input:

  • 链表头结点 :: ListNode
  • 另一个链表头结点 :: ListNode

Output:

  • 相加后链表头结点 :: ListNode

Intuition:

这题就很直接的每个元素相加就好,但是tricky的地方在于如何处理进位。很显然我们需要一个变量来存储当前位的进位状况然后在下一位的时候添加上。

Code:

TC: (n) SC: (1)

public ListNode addTwoNum(ListNode l1, ListNode l2){
  ListNode dummy = new ListNode(-1);
  ListNode p = dummy;
  ListNode p1 = l1;
  ListNode p2 = l2;
  int sum = 0;
  int carry = 0;

  while (p1 != null && p2 != null){
    if (p1 != null){
      sum += p1.val;
      p1 = p1.next;
    }
    
    if (p2 != null){
      sum += p2.val;
      p2 = p2.next;
    }
    //save carry for next round addition
    carry = sum / 10;
    p.next = new ListNode( sum % 10);
    p = p.next;
    sum /= 10;
  }
  if(carry == 1) p.next = new ListNode(1);
  return dummy.next;
}

题目:Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains 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 list is not allowed.

Input:

  • 链表头结点 :: ListNode
  • 另一个链表头结点 :: ListNode

Output:

  • 相加后链表头结点 :: ListNode

Intuition:

跟第一题不同的地方就在于这回链表表示的数字跟我们默认的数字是一样的,最小位在左边。需要解决的问题其实还是进位,不过我们得倒着加,即把左边的高位数的数先存着,低位数加完后再来加高位数。是不是听着挺耳熟?这不就是先进后出嘛?所以我们需要一个stack。

Code:

TC: (n) SC: (n)

public ListNode addTwoNum(ListNode l1, ListNode l2){
  Deque stk1 = new ArrayDeque<>();
  ListNode dummy = new ListNode(-1);
  ListNode p = dummy;
  ListNode p1 = l1;
  ListNode p2 = l2;
  int sum = 0;
  int carry = 0;
  //use stack to reverse order
  while (p1 != null && p2 != null){
    if (p1 != null){
      stk1.push(p1.val);
      p1 = p1.next;
    }
    
    if (p2 != null){
      stk2.push(p2.val);
      p2 = p2.next;
    }
  }
    
  while(!stk1.isEmpty() || !stk2.isEmpty()){
    //save carry for next round addition
    if (!stk1.isEmpty()){
      sum += stk1.pop()
    }
    
    if (!stk2.isEmpty()){
      sum += stk1.pop()
    }
    carry = sum / 10;
    ListNode cur = new ListNode(carry);
    cur.next = ListNode( sum % 10);
    cur =
    p = p.next;
    sum /= 10;
  }
  return dummy.next;
}

Reference

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

你可能感兴趣的:(链表相加问题(cont))