leetcode: 2. Add Two Numbers

来源:互联网 发布:linux如何切换用户 编辑:程序博客网 时间:2024/06/14 22:30

一、描述:

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: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

二、思路

  • 由于输入是反序放入链表的,如123以321的顺序放入到链表当中,所以应该从左向右进位
  • 链表长度可能不相同,两个链表对应的位相加时,短链表的值默认为0
  • 遍历完两个链表时,处理最高位可能进位的情况

三、代码(Java)

public class Solution{  public ListNode addTwoNumbers(ListNode l1, ListNode l2){      //分别指向链表的头结点      ListNode p = l1;      ListNode q = l2;      //要返回的链表       ListNode res = new ListNode(0);      ListNode res_tail = res;      int carry = 0;//保存进位      while (p != null || q != null){          int s = (p == null ? 0 : p.val) + (q == null ? 0 : q.val) + carry;          res_tail.next = new ListNode(s % 10);          res_tail = res_tail.next;          carry = s / 10;          if (p != null){              p = p.next;          }           if (q != null){              q = q.next;          }      }      //处理最高位进位问题      if (carry != 0){          res_tail.next = new ListNode(1);          res_tail = res_tail.next;      }      return res.next;  }}
原创粉丝点击