注:是高位在前
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
翻转链表方法
#include <stdio.h>
#include <algorithm>
#include<vector>
#include<set>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
void out_list(ListNode *list){
while(list!= nullptr){
cout<< list->val;
list =list->next;
}
}
class Solution {
public:
//翻转链表方法
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//先给l1 l2翻转链表
l1 = reverse_list(l1);
l2 = reverse_list(l2);
ListNode *res = normal_add(l1,l2);
res = reverse_list(res);
out_list(res);
return res;
}
ListNode* reverse_list(ListNode* l1){
ListNode *pre = l1;
ListNode *cur = l1->next;
pre->next = nullptr;
while(cur!=nullptr){// cur一直往后走,直到nullptr
ListNode *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
//out_list(pre);
return pre;
}
ListNode* normal_add(ListNode* l1,ListNode* l2){
int t=0;
ListNode *head = new ListNode();
ListNode* res = head;
while(l1!=nullptr && l2!= nullptr){
t =t+l1->val;
l1 =l1->next;
t =t+l2->val;
l2 =l2->next;
ListNode *p = new ListNode(t%10);
head->next = p;
head = p;
t = t/10;
}
while(l1!=nullptr){
t =t+l1->val;
l1 =l1->next;
ListNode *p = new ListNode(t%10);
head->next = p;
head = p;
t = t/10;
}
while(l2!=nullptr){
t =t+l2->val;
l2 =l2->next;
ListNode *p = new ListNode(t%10);
head->next = p;
head = p;
t = t/10;
}
if(t==1){
ListNode *p = new ListNode(t);
head->next = p;
}
return res->next;
}
};
int main()
{
printf("Hello World");
Solution *myslo = new Solution();
//vector<int> v1 = {7,2,4,3}; vector<int> v2 = {5,6,4}; //输出:[7,8,0,7]
vector<int> v1 = {5}; vector<int> v2 = {5}; //输出:[7,8,0,7]
ListNode *p = new ListNode(v1[0]);
ListNode *l1 = p;
for(int i=1;i<v1.size();i++){
ListNode *cur = new ListNode(v1[i]);
p->next = cur;
p = cur;
}
ListNode *p2 = new ListNode(v2[0]);
ListNode *l2 = p2;
for(int i=1;i<v2.size();i++){
ListNode *cur = new ListNode(v2[i]);
p2->next = cur;
p2 = cur;
}
ListNode *res = myslo->addTwoNumbers( l1 ,l2);
cout<<endl<< res->val;
delete myslo;
return 0;
}