力扣(leetcode)2.两数(树)相加完整代码
代码如下:
//
// main.cpp
// leetcode-2-两数相加
//
// Created by 123 on 9/18/21.
//
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode() : val(0),next(nullptr){}
ListNode(int t) : val(t),next(nullptr){}
ListNode(int t,ListNode* tNext) : val(t),next(tNext){}
};
class Solution{
public:
ListNode* add(ListNode* l1,ListNode* l2)
{
ListNode* head = new ListNode(0);
ListNode* tail = head;
int c = 0;
while(l1 || l2)
{
int l1V = 0;
int l2V = 0;
if(l1)
{
l1V = l1->val;
}
if(l2)
{
l2V = l2->val;
}
// cout << l1V << " " << l2V << endl;
int sum = l1V+ l2V + c;
c = sum/10;
tail->next = new ListNode(sum%10);
tail = tail->next;
if(l1)
{
l1 = l1->next;
}
if(l2)
{
l2 = l2->next;
}
}
if(c)
{
tail->next = new ListNode(c);
}
return head->next;
}
};
int main(int argc, const char * argv[]) {
ListNode* l1 = new ListNode(0);
ListNode* l2 = new ListNode(0);
ListNode* p1 = l1;
ListNode* p2 = l2;
int l1V,l2V;
while(cin >> l1V)
{
p1->next = new ListNode(l1V);
p1 = p1->next;
// cout << p1->val;
if(cin.get() == '\n')
{
break;
}
}
while(cin >> l2V)
{
p2->next = new ListNode(l2V);
p2 = p2->next;
// cout << p2->val;
if(cin.get() == '\n')
{
break;
}
}
// cout << l1->next->val << l1->next->next->val << l1->next->next->next->val;
// cout << l2->next->val << l2->next->next->val << l2->next->next->next->val;
Solution s;
ListNode* res = s.add(l1->next, l2->next);
while(res)
{
cout << res->val;
if(res)
{
res = res->next;
}
}
cout << endl;
return 0;
}
遇见的问题
1、链表的输入输出。
2、定义链表头指针的时候,如果这个指针不会被再定义的话,需要初始化,否者会内存溢出。
3、相似的程序在复制粘贴的时候需要注意该变的变量名称一定要改变。
最主要的还是标准的输入输出。