careercup2.4
来源:互联网 发布:sql截掉字符串 编辑:程序博客网 时间:2024/06/05 09:34
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;elsereturn 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 testsystem("pause");}
- careercup2.4
- careercup2.4
- careercup2
- careercup2.1
- careercup2.2
- careercup2.3
- careercup2.5
- CareerCup2.5
- CareerCup2.3 删除最中间那个,或者删除给出任意一个节点(只能得到这个节点的pointer)
- 4
- 4
- (4)
- 4
- 4
- 4
- 4
- 4
- 4
- android repo 切换分支
- GDI内存泄露小结
- 20、C++运算符重载之输入输出运算符的重载
- int main(int argc, char* argv[])
- C++的运算符重载
- careercup2.4
- 非模态对话框的创建与销毁
- 数学专项number_theory:UVa 10090
- win7 时间和时区修改不了的问题
- 21、C++类的继承
- java高级工程师-----JSON和XML的使用
- Bitmap处理之Bitmap缓存
- 开篇文字
- 跨站测试与利用中的绕过技术