Professional Documents
Culture Documents
Danh Sach Lien Ket
Danh Sach Lien Ket
h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
//khoi tao
void Init(NODEPTR &phead){
phead=NULL;
}
// Tác vu kiem tra rong
int IsEmpty(NODEPTR phead){
return (phead==NULL);
}
// Tác vu tao nut x
NODEPTR CreateNode(int x){
NODEPTR p=new Node;
p->info=x;
p->next=NULL;
return p;
}
// Tác vu InsertLast
void InsertLast(NODEPTR &phead, int x){
NODEPTR tam=CreateNode(x);
NODEPTR p;
p = phead;
if (phead==NULL)
phead=tam;
else
{
NODEPTR ptemp=phead;
while (ptemp->next!=NULL)
ptemp = ptemp->next;
ptemp->next=tam;
}
}
//them node p vao dau danh sach//
void InsertFirst(NODEPTR &phead, int x)
{
NODEPTR p=CreateNode(x);
if(phead==NULL)
phead=p;
else
{
p->next=phead;
phead=p;
}
}
// Tác vu nodePointer: xac dinh nut thu i.
NODEPTR NodePointer(NODEPTR phead, int i){
NODEPTR q=phead;
int vitri=0;
while(q!=NULL && vitri<i){
q=q->next;
vitri++;
}
return q;
}
//them node p vao vi tri bat ki//
void InsertAfter(NODEPTR q, int m)
{
NODEPTR tam;
if(q!=NULL)
{
tam=CreateNode(m);
tam->next=q->next;
q->next=tam;
}
}
// Nhap danh sach
void Input(NODEPTR &phead)
{
NODEPTR p;
char s[max];
int x;
Init(phead);
while(1)
{
gets(s);
if(*s==0) break;
x=atoi(s); //phai khai bao #include <stdlib.h>
InsertLast(phead,x);
}
}
//Hàm chính
int main()
{
//khai báo các bien quan lý danh sách
Node* phead; //bien tro den nút dau tiên trong danh sách
Init(phead); //khoi tao danh sách liên ket ban dau chua có nút nào
//Nhap danh sach
printf("\n Nhap danh sach: Nhan phim Enter 2 lan de ket thuc! ");//khi
nhap danh sach nho enter moi phan tu, khong mac cong no dinh lai//
Input(phead);
//Xuat danh sach
printf("\n Danh sach sau khi nhap: ");
Output(phead);
//them node p vao dau danh sach//
int x;
printf("\n");
printf("nhap gia tri them o dau danh sach: ");
scanf("%d",&x);
InsertFirst(phead,x);
Output(phead);
int m;
int pos;
NODEPTR q;
printf("\n");
printf("nhap gia tri them o vi tri bat ki: ");
scanf("%d",&m);
printf("nhap vi tri muon them: ");
scanf("%d",&pos);
if(pos==0)
InsertFirst(phead,m);
else
{
q=NodePointer(phead,pos-1);
if(q==NULL)
printf("vi tri them khong hop le");
else
InsertAfter(q,m);
}
Output(phead);
int k;
printf("\n");
printf("nhap gia tri can tim: ");
scanf("%d",&k);
NODEPTR kq= Search(phead,k);
if(kq==NULL)
printf("nhap lai gia tri chan\n");
SortUp(phead,k);
printf("danh sach sau khi sap xep tang dan: \n");
Output(phead);
printf("\n");
return 0;
}