#include "stdafx.h"
#include<iostream>
using namespace std;
struct linklist {
struct linklist* next;
int data;
};
linklist *create();//链表建立
void remove(linklist *head);//去除重复项
linklist *findnthlast(linklist *head,int n);//找到倒数第n个元素
linklist *addlink(linklist *q,linklist *p);//链表对应相加(低位在前,高位在后,考虑进位)
void print(linklist *head);
int main()
{
linklist *p,*head,*head1,*res;
head=create();
head1=create();
res=addlink(head1,head);
/*remove(head);
cout<<findnthlast(head,3)->data<<endl;*/
print(head);
print(head1);
print(res);
}
linklist* create()
{
int input;
linklist *p,*n,*head;
head=new linklist;
if(cin>>head->data)
head->next=NULL;
else
{
delete head;
return NULL;
}
p=head;
while (cin>>input)
{
n=new linklist;
n->data=input;
n->next=NULL;
p->next=n;
p=n;
}
//cin清标志位和清缓冲区!!
cin.clear();
cin.sync();
return head;
}
void print(linklist *head)
{
if(head==NULL) cout<<"Empty linklist";
linklist *t=head;
while(t!=NULL)
{
cout<<t->data<<' ';
t=t->next;
}
cout<<endl;
}
void remove(linklist *head)
{
linklist *p=head,*q,*s;
while (p!=NULL) //!!
{
q=p->next;
s=p;
int data=p->data;
while(q!=NULL)
{
if(q->data==data)
{
s->next=q->next;
delete q; //Attention
q=s->next;
}
else {s=q;q=q->next;}
}
p=p->next;
}
}
linklist *findnthlast(linklist *head,int n)
{
if(head==NULL) return NULL;
linklist*p=head,*q=head;
int cnt=n; //!!
while(q!=NULL) //!!
{
if (cnt>0)
{
q=q->next;
--cnt;
}
else
{
p=p->next;
q=q->next;
}
}
if(cnt==0) return p;
else return NULL;
}
linklist *addlink(linklist *q,linklist *p)
{
if(q==NULL) return p;
if(p==NULL) return q;
int cnt=0;
linklist *t,*res=NULL;
while (q!=NULL&&p!=NULL)
{
linklist *r=new linklist;
int sum=q->data+p->data+cnt;
r->data=sum%10;
r->next=NULL;
cnt=sum/10;
if (res==NULL)
{
res=r;
t=r;
}
else
{
t->next=r;
t=r;
}
q=q->next;
p=p->next;
}
while(q!=NULL)
{
linklist *r=new linklist;
r->data=(q->data+cnt)%10;
cnt=(q->data+cnt)/10;
r->next=NULL;
t->next=r;
t=r;
q=q->next;
}
while(p!=NULL)
{
linklist *r=new linklist;
r->data=(p->data+cnt)%10;
cnt=(p->data+cnt)/10;
r->next=NULL;
t->next=r;
t=r;
p=p->next;
}
if (cnt>0)
{
linklist* r=new linklist;
r->data=cnt;
r->next=NULL;
t->next=r;
}
return res;
}
链表相关
最新推荐文章于 2024-09-07 05:15:02 发布