Cộng hai số lớn bằng DSLK đơn
PHP Code:
#include "stddef.h"
#include "conio.h"
#include "stdio.h"
typedef struct tagNode
{
int info;
struct tagNode *pNext;
}Node;
typedef struct
{
Node *Head;
Node *Tail;
}List;
void CreateList(List &l)
{
l.Head=NULL;
l.Tail=NULL;
}
Node *CreateNode(int x)
{
Node *p;
p=new Node;
p->info=x;
p->pNext=NULL;
return p;
}
void AddHead(List &l, Node *p)
{
if(l.Head==NULL)
{
l.Head=p;
l.Tail=p;
}
else
{
p->pNext=l.Head;
l.Head=p;
}
}
void AddTail(List &l,Node *p)
{
if(l.Head==NULL)
{
l.Head=p;
l.Tail=p;
}
else
{
l.Tail->pNext=p;
l.Tail=p;
}
}
int DeleteHead(List &l,int &x)
{
Node *p;
if(l.Head!=NULL)
{
p=l.Head; x=p->info;
l.Head=p->pNext;
if(l.Head==NULL)
l.Tail=NULL;
delete p;
return 1;
}
return 0;
}
void PrintList(List l)
{
Node *p;
p=l.Head;
while(p!=NULL)
{
printf("%d",p->info);
p=p->pNext;
}
}
void ThanhLapListKhiNhap(List &l)
{
char ch;
Node *p;
int x,tam;
do
{
ch=getch();
if((ch>='0')&&(ch<='9'))
{
putch(ch);
x=ch-48;
p=CreateNode(x);
AddHead(l,p);
}
else
{
if(ch==8)
{
putch(ch);
putch(' ');
putch(ch);
DeleteHead(l,tam);;
}
}
}while(ch!=13);
}
List Cong_Hai_So_Lon(List l1,List l2)
{
int x,du=0,nho=0;
Node *p;
p=l1.Head;
Node *q;
q=l2.Head;
List LKet_qua;
CreateList(LKet_qua);
while(p!=NULL||q!=NULL)
{
if(p==NULL)
x=q->info+nho;
if(q==NULL)
x=p->info+nho;
if(p!=NULL&&q!=NULL)
x=p->info+q->info+nho;
if(p->pNext!=NULL||q->pNext!=NULL)
{
if(x>=10)
{
du=x-10;
nho=1;
}
else
{
du=x;
nho=0;
}
}
else
{
du=x;
nho=0;
}
Node *k;
k=CreateNode(du);
AddTail(LKet_qua,k);
p=p->pNext;
q=q->pNext;
}
return LKet_qua;
}
void InNguoc(List l)
{
Node *p=l.Head;
int a[100],i=0;
while(p!=NULL)
{
a[i]=p->info;
i++;
p=p->pNext;
}
for(int j=i-1;j>=0;j--)
printf("%d",a[j]);
}
void main()
{
clrscr();
textmode(C80);
List l1,l2;
CreateList(l1);
CreateList(l2);
printf("\nNhap so lon thu nhat : ");
ThanhLapListKhiNhap(l1);
printf("\nNhap so lon thu hai : ");
ThanhLapListKhiNhap(l2);
printf("\n\nSo a : ");
InNguoc(l1);
printf("\nSo b : ");
InNguoc(l2);
printf("\nKet Qua phep cong: a+b=");
List xuatKQ=Cong_Hai_So_Lon(l1,l2);
// PrintList(xuatKQ);
//PrintList(l);
InNguoc(xuatKQ);
getch();
}