Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Chuong trinh minh hoa danh sach lien ket don - DSL
- //by FamiHug@FAMILUG on 16.12.2010
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct hehe{
- int info;
- struct hehe* link;
- } dsl;
- dsl* Init_DSL(dsl*);
- dsl* Insert_Head(dsl*,int);
- dsl* Insert_Tail(dsl* l,int x);
- dsl* Delete_Head(dsl* l);
- dsl* Delete_Tail(dsl* l);
- void Print_DSL(dsl*);
- int main()
- {
- dsl* l=NULL;
- int x,n=-1,i;
- l=Init_DSL(l);
- //Nhap so phan tu
- while(n<0)
- {
- printf("So phan tu cua ds:");
- scanf("%d",&n);
- if(n<0) printf("So phan tu phai lon hon hoac bang 0, nhap lai\n");
- else break;
- }
- //Nhap noi dung cac phan tu theo kieu them dau
- for(i=1;i<=n;i++)
- {
- printf("x%d= ",i);
- scanf("%d",&x);
- l=Insert_Head(l,x);
- }
- //In danh sach
- Print_DSL(l);
- //Them duoi
- printf("Nhap phan tu them vao duoi: ");
- scanf("%d",&x);
- l=Insert_Tail(l,x);
- //IN ds
- Print_DSL(l);
- //Xoa dau
- l=Delete_Head(l);
- l=Delete_Head(l);
- //IN ds
- Print_DSL(l);
- l=Delete_Tail(l);
- Print_DSL(l);
- return 0;
- }
- dsl * Init_DSL(dsl* l)
- {
- return NULL;
- }
- dsl* Insert_Head(dsl* l,int x)
- {
- printf("Them dau: %d",x);
- printf("\n");
- dsl* p=(dsl*)malloc(sizeof(dsl));
- p->info=x;
- if(l==NULL)
- {
- p->link=NULL;
- l=p;
- }
- else
- {
- p->link=l;
- l=p;
- }
- return l;
- }
- dsl* Insert_Tail(dsl* l,int x)
- {
- dsl* t=l;
- dsl* p=(dsl*)malloc(sizeof(dsl));
- p->info=x;
- p->link=NULL;
- printf("Them duoi: %d",x);
- printf("\n");
- if(t==NULL)
- {
- l=p;
- }
- else
- {
- while(t->link!=NULL)
- {
- t=t->link;
- }
- t->link=p;
- }
- return l;
- }
- //Delete
- dsl* Delete_Head(dsl* l)
- {
- dsl* t=NULL;
- printf("Xoa dau: ");
- if(l==NULL) printf("Danh sach rong! Khong the xoa dau\n");
- else
- {
- if(l->link==NULL)
- {
- t=l;
- l=NULL;
- free(t);
- }
- else
- {
- t=l;
- l=l->link;
- free(t);
- }
- printf("Da xoa phan tu dau tien cua danh sach!\n");
- }
- return l;
- }
- dsl* Delete_Tail(dsl* l)
- {
- printf("Xoa duoi: ");
- if(l==NULL)
- printf("Danh sach rong! Khong the xoa duoi.\n");
- else
- {
- dsl* t=l;
- if(l->link==NULL)//chi co 1 pt
- {
- t=l;
- l=NULL;
- free(t);
- }
- else
- {
- while(t->link->link!=NULL)
- t=t->link;
- dsl* q=t->link;
- t->link=NULL;
- free(q);
- }
- printf("Da xoa phan tu duoi!\n");
- }
- return l;
- }
- //Visit
- void Print_DSL(dsl* l)
- {
- dsl* t=l;
- if(t==NULL) printf("Danh sach: RONG \n");
- else
- {
- printf("Danh sach: ");
- while(t!=NULL)
- {
- printf("%2d",t->info);
- t=t->link;
- }
- printf("\n");
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement