leetcode Add Two Numbers

来源:互联网 发布:宾馆收费系统源码 编辑:程序博客网 时间:2024/06/18 15:47
#include <iostream>#include <vector>using namespace std;/** * 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) {int val = 0;int carry = 0;ListNode *p1 = NULL;ListNode *p2 = NULL;ListNode *head = NULL;ListNode *pcur = NULL;while (l1!=NULL || l2!=NULL){if (l1!=NULL)val += l1->val;if (l2!=NULL)val += l2->val;val += carry;carry = val/10;val %= 10;ListNode *newnode = new ListNode(val);val = 0;if (head==NULL){head = newnode;pcur = head;}else{pcur->next = newnode;pcur = newnode;}if (l1!=NULL)l1 = l1->next;if (l2!=NULL)l2 = l2->next;}if (carry>0){ListNode *newnode = new ListNode(carry);pcur->next = newnode;}return head;    }};int main(){ListNode *head = new ListNode(2);ListNode *pcur = NULL;pcur = new ListNode(4);head->next = pcur;pcur->next = new ListNode(3);ListNode *head2 = new ListNode(5);ListNode *pcur2 = NULL;pcur2 = new ListNode(6);head2->next = pcur2;pcur2->next = new ListNode(4);Solution s;ListNode *ret = s.addTwoNumbers(head,head2);while(ret){cout<<ret->val<<" ";ret = ret->next;}return 0;}

0 0
原创粉丝点击