目标就是把这个帖子上面的链表题都用c++写一遍,第一天大概写了一半。
看到这个大神的解是没太懂,想打出来模拟下太累了。。明天接着写,试图不看答案写完。
2. Add Two Numbers
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0;
ListNode res(0);
ListNode *cur=&res;
while (carry||l1||l2) {
carry+=(l1?l1->val:0)+(l2?l2->val:0);
cur->next=new ListNode(carry%10);
cur=cur->next;
carry/=10;
if (l1) l1=l1->next;
if (l2) l2=l2->next;
}
return res.next;
}
};
206. Reverse Linked List
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev=NULL;
ListNode *curr=head;
ListNode