文章目录
昨日留下的坑sizeof()用法
sizeof运算符返回一条表达式或一个类型名字所占的字节数。如果要用sizeof来计算数组的大小时应该这样
#include <iostream>
using namespace std;
int main(){
int x[10];
cout << "数组x的个数为"<< sizeof(x) / sizeof(*x) << endl;
system("pause");
return 0;
}
今日题目两数求和https://leetcode.cn/problems/add-two-numbers/
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
这题目有点难啊。。。
第一步知道结构体Listnode是什么
Definition for singly-linked list.
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) {}
};
突然想起来,,链表这种数据结构刚看过一点
额终于理解为啥说一道Leecode做一天了,先当一次cv侠,这里是leecode官方给出的代码https://leetcode.cn/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode-solution/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = new ListNode(sum % 10);
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry > 0) {
tail->next = new ListNode(carry);
}
return head;
}
};
留下坑
自己编写一个。。。。。。找找思路