2. Add Two Numbers

Posted by Csming on 2017-04-25

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


题解与理解

  • 题意大致是:给定两个链表,链表的每个节点是一个个位数,求两个链表的各个节点的和,并且满10进到下一位

解题用了一个辅助的链表dummy作为结果,并且用一个p链表赋值为dummy用于遍历;
利用一个int型整数x,作为各个节点的和;

这题没有什么特别难的地方;
需要注意的,主要在于当链表l1,l2遍历到末尾的时候怎么处理;即:一长一短的情况;

之前寒假刷了一遍剑指offer,然后发现处理leetcode的题目,其实非常多是需要注意一些特殊输入情况的;

解题源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int x = 0 ;
ListNode p, dummy = new ListNode(0);
p = dummy;
while(l1!=null | l2!=null | x !=0){
if(l1!=null){
x += l1.val;
l1 = l1.next;
}
if(l2!=null){
x +=l2.val;
l2 = l2.next;
}
p.next = new ListNode(x%10);
x = x/10;
p = p.next;
}
return dummy.next;
}
}