最近一直在忙实验室项目的事情,好久没写代码了,手太生了,所以去leetcode官网随便找了两个简单题刷了一下,第一个一遍就通过了,第二个还是有点问题。感觉这种东西就得多练。不然会一直退步退步,下面是我写的两个题的解法,仅供参考:(先写一题吧下一题之后补上)
Add Two Numbers
//C/C++解法
/*** Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
__author__yaojianpeng
//C/C++解法
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head=new ListNode(0);
ListNode *pre=head;
int carry=0;
while (l1!=NULL||l2!=NULL){
int a1=0;
if (l1!=NULL)
{a1=l1->val;
l1=l1->next;
}
int a2=0;
if (l2!=NULL)
{a2=l2->val;
l2=l2->next;
}
int value=a1+a2+carry;
pre->next=new ListNode(value%10);
carry=value/10;
pre=pre->next;
}
if (carry>0)
pre->next=new ListNode(carry);
return head->next;
}
};