题目描述:
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
思路:
链表每一个结点为整数的一位数字,且链表为整数的倒序排列,即从链表头开始是整数最低位数字。因此每位数字相加即可,可能会出现三种情况:
- l1、l2当前结点均存在,则结果为两结点值和前一位进位值相加对10取余,且要计算对后面的进位。
- l1、l2当前结点只有一个存在,则结果为该结点值和前一位进位值相加对10取余,且要计算对后面的进位。
- l1、l2当前节点均不存在,则判断前一位进位值。若为1,则结果为1;若为0则计算结束。
C语言解法:
|
|
C++解法:
|
|