Add Two Numbers

来源:互联网 发布:江湖婚庆3.0源码 编辑:程序博客网 时间:2024/06/16 06:41

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;    }};
0 0
原创粉丝点击