题目:假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:0≤n,m≤1000000,链表任意值 0≤val≤9
要求:空间复杂度 O(n),时间复杂度 O(n)
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
有两种解法,代码如下:
#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) :val(x), next(nullptr) {}
};
//链表的翻转
ListNode* REVERSEList(ListNode* L) {
ListNode* cur = L;
ListNode* prev = NULL;
while (cur) {
ListNode* tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
//两个链表相加(使用栈)
ListNode* addList1(ListNode* head1, ListNode* head2) {
stack<int> x1, x2;//用来存储两个链表的数据
while (head1) {
x1.push(head1->val);
head1 = head1->next;
}
while (head2) {
x2.push(head2->val);
head2 = head2->next;
}
int cnt = 0;//如果两个值的和>10,就会产生进位,这个用来存储进位
int sum = 0;
ListNode* res = NULL;
while (!x1.empty() || !x2.empty()) {
int s1 = x1.empty() ? 0 : x1.top();
int s2 = x2.empty() ? 0 : x2.top();
if (!x1.empty()) x1.pop();
if (!x2.empty()) x2.pop();
sum = s1 + s2 + cnt;//当前这一位的总和
cnt = sum / 10;//查看当前加和是否有进位
//进行当前节点的插入
ListNode* tmpNode = new ListNode(sum % 10);
tmpNode->next = res;
res = tmpNode;
}
if (cnt > 0) {
ListNode* tmpNode = new ListNode(cnt);
tmpNode->next = res;
res = tmpNode;
}
return res;
}
//两个链表相加(使用链表翻转)
ListNode* addList2(ListNode* head1, ListNode* head2) {
ListNode* newHead1 = REVERSEList(head1);
ListNode* newHead2 = REVERSEList(head2);
int cnt = 0;
ListNode* res = nullptr;
while (newHead1 || newHead2) {
if (!newHead1) return newHead2;
if (!newHead2) return newHead1;
int x1 = (newHead1 != NULL) ? newHead1->val : 0;
int x2 = (newHead2 != NULL) ? newHead2->val : 0;
int sum = x1 + x2 + cnt;
cnt = sum / 10;
ListNode* tmpNode = new ListNode(sum % 10);
tmpNode->next = res;
res = tmpNode;
if (newHead1->next)newHead1 = newHead1->next;
if (newHead2->next)newHead2 = newHead2->next;
}
if (cnt > 0) {
ListNode* tmpNode = new ListNode(cnt);
tmpNode->next = res;
res = tmpNode;
}
return res;
}