careercup2.4
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
用链表来表示两个数。链表的每个节点包含该数的某位上的数字。各个位上的数字是以逆序存储的,这样第一位的数字存储在链表头。
输入中两个括号内的内容是两个链表。
3是第一个数的各位,5是第二个数的各位,两个数十位上分别是1,9,百位上分别是5.2
输出是和。和的个位为8,十位为0,百位为8
#include<iostream> using namespace std; struct node{ int data; node *next; }; node * add(node *first,node *second){ node *head=new node(); //list1保存第一个链表的位置 //list2保存第二个链表的位置 //变量i用来保存进位 //当前位的数据为两个链表上对应位置的数据之和- //加上进位之后mod 10(%10)而得 node *list1=first; node *list2=second; int i=0; if(list1==NULL&&list2==NULL) return NULL; if(list1!=NULL&&list2!=NULL){ head->data=(list1->data+list2->data+i)%10; i=(list1->data+list2->data+i)/10; list1=list1->next; list2=list2->next; } else{ if(list1==NULL) return list2; else return list1; } node *cur=head; while(list1!=NULL&&list2!=NULL){ node *temp=new node(); temp->data=(list1->data+list2->data+i)%10; i=(list1->data+list2->data+i)/10; cur->next=temp; cur=cur->next; list1=list1->next; list2=list2->next; } while(list1!=NULL){ node *temp=new node(); temp->data=(list1->data+i)%10; i=(list1->data+i)/10; cur->next=temp; cur=cur->next; list1=list1->next; } while(list2!=NULL){ node *temp=new node(); temp->data=(list2->data+i)%10; i=(list2->data+i)/10; cur->next=temp; cur=cur->next; list2=list2->next; } return head; } int main(){ node *n1=new node(); n1->data=5; node *n2=new node(); n2->data=7; node *n3=new node(); n3->data=5; node *n4=new node(); n4->data=6; node *n5=new node(); n5->data=8; node *n6=new node(); n6->data=2; n1->next=n2; n2->next=n3; n3->next=NULL; n4->next=n5; n5->next=n6; n6->next=NULL; node *res=add(n1,n4); while(res!=NULL){ cout<<res->data<<" "<<endl; res=res->next; } //just for test system("pause"); }