Add Two Numbers

链接:https://oj.leetcode.com/problems/add-two-numbers/


链表的大数加法


/**
 * 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 *ans=new ListNode(0);
			ListNode *pos=ans;
			int tem=0;
			int sign=0;
			while(l1!=NULL&&l2!=NULL)
			{
				tem=l1->val+l2->val+sign;	
				pos->next=new ListNode(tem%10);
				sign=tem/10;
				pos=pos->next;
				if(l1->next==NULL&&l2->next==NULL&&sign!=0)
				{
					pos->next=new ListNode(sign);
					return ans->next;

				}
				if((l1->next==NULL&&l2->next!=NULL)||(l1->next!=NULL&&l2->next==NULL))
				{
					if(l2->next!=NULL)
						pos->next=l2->next;
					else if(l1->next!=NULL)
						pos->next=l1->next;
					pos=pos->next;
					if(sign!=0)
					{
						while(pos!=NULL&&sign!=0)
						{
							tem=(pos->val+sign);
							pos->val=tem%10;
							sign=tem/10;
							if(pos->next==NULL&&sign!=0)	
							{
								pos->next=new ListNode(sign);
								sign=0;
							}
							pos=pos->next;
						}
					}
					return ans->next;
				}
				l1=l1->next;
				l2=l2->next;
			}
			return ans->next;
		}
};


原文地址:https://www.cnblogs.com/frankM/p/4399436.html