1.主要是链表先创建下一个对象,再转移,而不是先转移到空指针再赋值
t = new ListNode((v1 + v2 + count1)%10);
count1 = (v1+v2+count1)/10;
t = t->next;
|
|
|
V
t->next = new ListNode((v1 + v2 + count1)%10);
count1 = (v1+v2+count1)/10;
t = t->next;
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
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) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = nullptr; ListNode* t = nullptr;
int count1 = 0;
while (l1 || l2)
{
int v1 = l1 ? l1->val : 0;
int v2 = l2 ? l2->val : 0;
if(!head)
{
t = head = new ListNode((v1 + v2)%10);
count1 = (v1+v2)/10;
}else
{
t->next = new ListNode((v1 + v2 + count1)%10);
count1 = (v1+v2+count1)/10;
t = t->next;
}
if(l1)
l1 = l1->next;
if(l2)
l2 = l2->next;
}
if(count1 != 0)
{
t->next = new ListNode(count1);
}
return head;
}
int main()
{
ListNode* head =new ListNode(2);
ListNode* v1 = head;
head->next =new ListNode(4);
head = head->next;
head->next =new ListNode(3);
ListNode* head2 =new ListNode(5);
ListNode* v2 = head2;
head2->next =new ListNode(6);
head2 = head2->next;
head2->next =new ListNode(4);
ListNode* v3 = addTwoNumbers(v1,v2);
int a = 0;
a = 1;
}
2.三目运算符
条件是否为真? 是 : 否
3.初始化
ListNode* a = nullptr;