You are given two linked lists representing two non-negative numbers. 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.
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *head = NULL, *prev = NULL;
int c = 0;
while (l1 != NULL || l2 != NULL || c != 0) {
if (l1 != NULL) {
c += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
c += l2->val;
l2 = l2->next;
}
ListNode *p = new ListNode(c % 10);
if (head == NULL) {
head = p;
}
else {
prev->next = p;
}
prev = p;
c /= 10;
}
return head;
}
};
本文介绍了一种解决两数相加问题的方法,通过链表形式存储数字,并以逆序方式排列各节点的数值。文章提供了一个简洁的C++代码示例,展示了如何将两个链表表示的非负整数相加,并返回结果作为新的链表。
289

被折叠的 条评论
为什么被折叠?



