难度中等323
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 8 -> 0 -> 7
不知道莫名的开心是哪来的?
思路就是用栈来存储链表里的数,然后倒着出来时候进行相加,最后在把链表反转一下。我还用到了之前写的题目代码,反转链表的代码。我感觉我有点多次一举,看别人写的代码长度都挺少的,我。。。
/**
* 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) {
stack<int> st1, st2;
while(l1 != NULL){
st1.push(l1->val);
l1 = l1->next;
}
while(l2 != NULL){
st2.push(l2->val);
l2 = l2->next;
}
ListNode* head = NULL, *tail = NULL;
int carry = 0;
while(!st1.empty() || !st2.empty()){
int n1 = 0, n2 = 0;
if(!st1.empty()){
n1 = st1.top();
st1.pop();
}
if(!st2.empty()){
n2 = st2.top();
st2.pop();
}
int sum = n1 + n2 + carry;
carry = sum / 10;
if(!head){
head = tail = new ListNode(sum % 10);
}else{
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
}
if(carry > 0){
tail->next = new ListNode(carry);
}
return reverseList(head);
}
ListNode* reverseList(ListNode* head) {
ListNode *pre = head;
ListNode *cur = NULL;
while(pre != NULL){
ListNode *tmp = pre->next;
pre->next = cur;
cur = pre;
pre = tmp;
}
return cur;
}
};
另外,反转链表函数用的挺熟,突然又有一个想法,先把两个链表反转一下然后直接进行加减,是不是也可以呢?
/**
* 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) {
ListNode* cl1 = reverseList(l1);
ListNode* cl2 = reverseList(l2);
ListNode* head = NULL, *tail = NULL;
int carry = 0;
while(l1 || l2){
int n1 = 0, n2 = 0;
if(l1){
n1 = cl1->val;
cl1 = cl1->next;
}
if(l2){
n2 = cl2->val;
cl2 = cl2->next;
}
int sum = n1 + n2 + carry;
carry = sum / 10;
if(!head){
head = tail = new ListNode(sum%10);
}else{
tail->next = new ListNode(sum%10);
tail = tail->next;
}
}
if(carry > 0){
tail->next = new ListNode(carry);
}
return head;
}
ListNode* reverseList(ListNode* head) {
ListNode *pre = head;
ListNode *cur = NULL;
while(pre != NULL){
ListNode *tmp = pre->next;
pre->next = cur;
cur = pre;
pre = tmp;
}
return cur;
}
};