1.Question:
2. Add Two Numbers
- Total Accepted: 206533
- Total Submissions: 804547
- Difficulty: Medium
- Contributors: Admin
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
2.Solution:
标准的链表的操作的题,本题我们模拟加法就可以了,注意进位,没有什么难的
3.Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* p=l1;
struct ListNode* w=l2;
int lenp=0;
int lenw=0;
while(p!=NULL) p=p->next,lenp++;
while(w!=NULL) w=w->next,lenw++;
p=l1;
w=l2;
//struct ListNode* h;
int un=0;
if(lenw>=lenp)
{
while(w!=NULL)
{
if(p!=NULL) w->val+=p->val+un;
else w->val+=un;
un=0;
if(p!=NULL) p=p->next;
if(w->val>=10) w->val-=10,un++;
w=w->next;
}
if(un!=0)
{
w=l2;
while(w->next!=NULL) w=w->next;
struct ListNode* h=(struct ListNode*)malloc(sizeof(struct ListNode*));
h->val=un;
h->next=NULL;
w->next=h;
}
return l2;
}
else
{
while(p!=NULL)
{
if(w!=NULL) p->val+=w->val+un;
else p->val+=un;
un=0;
if(w!=NULL) w=w->next;
if(p->val>=10) p->val-=10,un++;
p=p->next;
}
if(un!=0)
{
p=l1;
while(p->next!=NULL) p=p->next;
struct ListNode* h=(struct ListNode*)malloc(sizeof(struct ListNode*));
h->val=un;
un=0;
h->next=NULL;
p->next=h;
}
return l1;
}
}