LeetCode 打卡
两数相加:
/**
* 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) {
ListNode *headNode=nullptr;
ListNode *tailNode=nullptr;
int carry=0;
while(l1 || l2)
{
int count=0;
if(l1)
{
count=count+l1->val;
l1=l1->next;
}
if(l2)
{
count=count+l2->val;
l2=l2->next;
}
count=count+carry;
if(!headNode)
{
if(0==count)
{
headNode=new ListNode(0);
carry=0;
tailNode=headNode;
}
else
{
headNode=new ListNode(count%10);
carry=count/10;
tailNode=headNode;
}
}
else{
if(0==count)
{
tailNode->next= new ListNode(0);
carry=0;
tailNode=tailNode->next;
}
else
{
tailNode->next=new ListNode(count%10);
carry=count/10;
tailNode=tailNode->next;
}
}
}
if(0!=carry)
{
tailNode->next=new ListNode(carry);
}
return headNode;
}
};
反转链表
/**
* 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) {
if(head==nullptr){return nullptr;}
ListNode *curNode=head;
while(head->next!=nullptr)
{
ListNode *lastPre=head->next->next;
head->next->next=curNode;
curNode=head->next;
head->next=lastPre;
}
return curNode;
}
};