您的位置:首页 > 其它

Add Two Numbers

2015-05-08 11:18 120 查看
1、新建一个链表,并赋值

ListNode *result=new ListNode(c%10);
if(head==NULL) head=result;
else prev->next=result;
prev=result;
return head;


题目:

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

思路:

1、用链表做加法,每个节点代表一位数;

2、记录进位;

3、新建链表,显示相加的结果,返回;

代码:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *prev=NULL;
ListNode *head=NULL;
int c=0;
while(l1!=NULL || l2!=NULL || c!=0)
{
if(l1!=NULL)
{
c+=l1->val;
l1=l1->next;
}
if(l2!=NULL)
{
c+=l2->val;
l2=l2->next;
}
ListNode *result=new ListNode(c%10);
if(head==NULL) head=result;
else prev->next=result;
prev=result;

c=c/10;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: