标签:
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
Linked List Math
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* ptr1=l1; ListNode* ptr2=l2; ListNode* head=NULL; ListNode* ptr; int jinwei=0; if(ptr1==NULL&&ptr2==NULL)//若都是空的则直接返回 return head; head=(ListNode*)malloc(sizeof(ListNode)); if(ptr1!=NULL&&ptr2!=NULL)//两个都不为空 { head->val=(ptr1->val+ptr2->val)%10; jinwei=(ptr1->val+ptr2->val)/10; } else if(ptr1==NULL&&ptr2!=NULL)//其中一个为空,也可以直接返回那个不为空的链表即可 return ptr2; else return ptr1; head->next=NULL; ptr=head; //下面是两个链表的第一个都不为空 while(1) { //这里若有一个为空的话就不再往后移了, if(ptr1!=NULL) ptr1=ptr1->next; if(ptr2!=NULL) ptr2=ptr2->next; if(ptr1==NULL&&ptr2==NULL)//若两个链表都已经到了最后为空的地方,就可以计算跳出循环了 { if(jinwei==1) { ListNode* temp2=(ListNode*)malloc(sizeof(ListNode)); temp2->val=1; temp2->next=NULL; ptr->next=temp2; ptr=temp2; } break; } //这里说明肯定最少有一个不是空的,还需要继续计算,继续循环 int a=0,b=0; if(ptr1!=NULL) a=ptr1->val; if(ptr2!=NULL) b=ptr2->val; ListNode* temp=(ListNode*)malloc(sizeof(ListNode)); temp->val=(a+b+jinwei)%10; jinwei=(a+b+jinwei)/10; temp->next=NULL; ptr->next=temp; ptr=temp; } return head; } int main() { ListNode* l1=(ListNode*)malloc(sizeof(ListNode)); l1->next=NULL; l1->val=0; ListNode* l2=(ListNode*)malloc(sizeof(ListNode)); l2->val=7; l2->next=(ListNode*)malloc(sizeof(ListNode)); l2->next->val=3; l2->next->next=NULL; ListNode* l3=addTwoNumbers(l1,l2); }
leetcode_2_题——Add Two Numbers(链表)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4486062.html