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.
exaple:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
理解题目为,数字两两相加,并朝下一位进位。
情况一:其中一个列表提前加完,将没加完的补充到需要输出的列表处。
情况二:同时加完,却仍有进位,需创建一个结点存储。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int up = 0;
ListNode *pNode = NULL, *pNext = NULL, *resList = NULL; //定义ListNode类型的指针
ListNode *p = l1, *q = l2;
while (p != NULL && q != NULL){
pNext = new ListNode(q->val + p->val + up);//将指针指向新的结点
up = pNext->val / 10;
pNext->val = pNext->val % 10;
if(resList == NULL){
resList = pNode = pNext;//保持头结点的不动
}
else{
pNode->next = pNext;//结点连接
pNode = pNext;
}
p = p->next;
q = q->next;
}
while (q != NULL){
//l2仍有剩余
pNext = new ListNode(q->val + up);
up = pNext->val / 10;
pNext->val = pNext->val % 10;
pNode->next = pNext;//结点连接
pNode = pNext;
q = q->next;
}
while (p != NULL){
//l1仍有剩余
pNext = new ListNode(p->val + up);
up = pNext->val / 10;
pNext->val = pNext->val % 10;
pNode->next = pNext;//结点连接
pNode = pNext;
p = p->next;
}
if (up != 0){
//都没有剩余,却仍有进位,需要再创建一个点
pNext = new ListNode(up);
pNode->next = pNext;
pNode = pNext;
}
return resList; //返回结果的头指针
}
};
知识点:指针、列表的使用,指针的向下移动