Tải bản đầy đủ (.pdf) (6 trang)

Code lập trình công nghệ thông tin

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (35.68 KB, 6 trang )

#include<stdio.h>
#include<conio.h>

struct node
{
int info;
struct node *next;
};
typedef node *listnode;
listnode *head;
void init(listnode *head)
{
*head=NULL;
}

void insert_first(listnode *head,int x)
{
listnode p;
p=new node;
p->info=x;
p->next= *head;
*head=p;
}

void insert_last(listnode *head,int x)
{
listnode p,q;


p=new node;
p->info=x;


p->next=NULL;
if(*head==NULL) *head=p;
else
{
q=*head;
while(q->next!=NULL)q=q->next;
q->next=p;
}
}
void delete_first(listnode *head)
{
listnode q;
if(*head!=NULL)
{
q=*head;
*head=q->next;
q->next=NULL;
delete(q);
}
}
void delete_last(listnode *head)
{
listnode q,r;
if((*head)->next==NULL)
{
delete_first(head);


return;
}

r=*head;
while(r->next!=NULL)
{
q=r;
r=r->next;
}
q->next=NULL;delete(r);
}
void output(listnode *head)
{
listnode p;
p=*head;
while(p!=NULL)
{
printf("%5d",p->info) ;
p=p->next;
}
}
int tong(listnode *head)
{
int t=0;
listnode p;
p=*head;
while(p!=NULL)
{


t+=p->info;
p=p->next;
} return t;

}
listnode search(listnode *head,int key)
{
listnode q;
q=*head;
while((q!=NULL)&&(q->info!=key)) q=q->next;
return q;
}
void main()
{
int chon,x,key;
listnode *head;
do
{
clrscr;
printf("\n 1 Nhap danh sach");
printf("\n 2 chen pt vao dau");
printf("\n 3 chen phan tu vao cuoi");
printf("\n 4 xoa pt cao dau");
printf("\n 5 xoa phan tu vao cuoi");
printf("\n 6 tinh tong");
printf("\n 7 tim key");
printf("\n 8 thoat");
printf("\n");
scanf("%d",&chon);


switch(chon)
{


case 1:
init(head);
break;
case 2:
printf("\nNhap x:");
scanf("%d",&x);
insert_first(head,x);
output(head);
break;
case 3:
printf("\nNhap x:");
scanf("%d",&x);
insert_last(head,x);
output(head);
break;
case 4:
delete_first(head);
output(head);
break;
case 5:
delete_last(head);
output(head);
break;
case 6:
output(head);


printf("\n Tong la %d",tong(head));
break;
case 7:

printf("\n nhap key:");
scanf("%d",&key);
output(head);
if((search(head,key)==NULL)) printf("\n ko tim thay %d",key);
else printf("\n tim thay %d",key);
break;
case 8:
break;
}
getch();
}
while(chon!=8);
}



×