面试题之陈利人 单链表和之恋

来源:互联网 发布:ping ip加端口 编辑:程序博客网 时间:2024/03/29 01:24

单链表和之恋

  • 真言

年轻人多听听音乐---周杰伦。给大家推荐一首歌 《单身礼物》,歌手赵凯。

  • 引言

题目已经过去很久,但是我不能放过自己,必须补上。我把自己的电脑屏幕调成黑白的啦,博客也只能看成黑白的啦。建议大家也调成黑白的,保护眼睛。

  • 题目

  • 思路

举个例子说吧,不知你们喜不喜欢图,我很喜欢,形象生动。。。。

  • 实验

  • 代码

test.cpp

#include<iostream>using namespace std;// declare size for listint const size = 30;// define class for listclass node{public:int d;node * next;node(){d = 0 ;next = NULL ;}};// function declare for add listnode * Add(node * La,node* Lb);int main(){// list for a and b without head nodenode *L_a = NULL ,*pa;node *L_b = NULL ,*pb;node * R = NULL ,*pr;for(int i= 0;i<size;i++ ){pa = new node;pb = new node;pa->d = rand() % 10;pb->d = rand() % 10;pa->next = L_a;L_a  = pa;pb->next = L_b;L_b = pb ;}cout<<"La="<<endl;pa = L_a;while (pa){cout<<pa->d<<" "; pa = pa->next ;}cout<<endl;cout<<"Lb="<<endl;pb = L_b;while(pb){cout<<pb->d<<" "; pb = pb->next;}cout<<endl;R = Add(L_a,L_b);cout<<"result="<<endl;pr = R;while(pr){cout<<pr->d<<" ";pr =pr->next;}cout<<endl;system("pause");return 0;}// function define for add listnode * Add(node * La,node* Lb){if(La == NULL)return Lb;else if(Lb == NULL)return NULL;node * result = NULL;node *pa = La,*pb = Lb,*pr;while(pa && pb){if((pa->d)<0 || (pa->d)>9 || (pb->d)<0 || (pb->d)>9){cout<<"exception of input add for list elem"<<endl;return NULL;}pr = new node ;pr->d = pa->d + pb->d;pr->next = result;result = pr;pa = pa->next;pb = pb->next;}pr = result;while(pr && pr->next){pr->next->d += (pr->d)/10 ;pr->d = (pr->d) %10;pr = pr->next;}// the max bit go forwardif((pr->d) >= 10){node * max = new node;max->d  = (pr->d) / 10;pr->d = (pr->d) % 10;max->next = NULL;pr->next = max ;}// reverse the list resultpr = result ;node * pnext = NULL ;while(pr && pr->next){pnext = pr->next;pr -> next = pr->next->next;pnext -> next = result;result = pnext;}while(result){if(result->d == 0)result = result->next;else break;}return result;}


 

1 0