Leetcode【4】:Add Two Numbers

来源:互联网 发布:mysql 行列转换 编辑:程序博客网 时间:2024/05/31 05:28
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。自己写的很繁琐,参考网上体会了一把代码简洁美。时间O(m+n)。

class Solution{public:ListNode *addTwoNumbers(ListNode *l1,ListNode *l2){ListNode *ptr1,*ptr2;ptr1=l1;ptr2=l2;ListNode *prev= new ListNode(-1);int carry=0;ListNode *head=prev;ListNode *pa,*pb;for(pa=l1,pb=l2;pa!=NULL || pb!=NULL;pa=(pa==NULL?NULL:pa->next),pb=(pb==NULL?NULL:pb->next),prev=prev->next)//条件写的真好。{int a=(pa==NULL?0:pa->val);int b=(pb==NULL?0:pb->val);int value=(a+b+carry)%10;carry=(a+b+carry)/10;prev->next= new ListNode(value);}if(carry==1)prev->next=new ListNode(carry);return head->next;}};


0 0
原创粉丝点击