Cấu trúc dữ liệu: Danh sách liên kết - Full Code

#include <stdio.h>
#include <malloc.h>
typedef int ElementType;
typedef struct
Node{
ElementType Element;
Node* Next;
};

typedef
Node* Position;
typedef
Position List;

void
MakeNullList(List &L){
L =(Node*)malloc(sizeof(Node));
L->Next = NULL;
}

int
EmptyList(List L){
return
(L->Next==NULL);
}

Position i2p(int i, List L){
Position P = L;
for
(int k=1;k<i;k++)
P=P->Next;
return
P;
}

void
InsertList(ElementType X, Position P, List &L){
Node* T = (Node*)malloc(sizeof(Node));
T->Element = X;
T->Next = P->Next;
P->Next = T;
}

void
InsertList(ElementType X, int P, List &L){
InsertList(X,i2p(P,L),L);
}


void
PrintList(List L){
Position P = L;
while
(P->Next!=NULL){
printf("%d ",P->Next->Element);
P=P->Next;
}

printf("\n");
}


//void DeleteList(Position P, List &L){
// if (L->Next!=NULL){
// Position T=P->Next;
// P->Next = T->Next;
// free (T);
// }
//}
void DeleteList(int p, List &L){
// DeleteList(i2p(P,L),L);
if (L->Next!=NULL){
Position P = i2p(p,L);
Position T=P->Next;
P->Next = T->Next;
free (T);
}
}


ElementType Retrieve(int P, List L){
//Retrieve(i2p(P,L),L);
return i2p(P,L)->Next->Element;
}


int
Locate(ElementType X, List L){
Position P = L;
int
i = 1;
while
(P->Next!=NULL){
if
(P->Next->Element==X)
return
i;
P=P->Next;
i=i+1;
}

return
i;
}

void
ReverseList(List &L){
List L2;
MakeNullList(L2);
Position P = L;
while
(P->Next!=NULL){
InsertList(P->Next->Element,1,L2);
P=P->Next;
}

L = L2;
}

void
SortList (List &L){
for
(Position P = L;P->Next!=NULL;P=P->Next){
ElementType min = P->Next->Element;
Position curMin = P;
for
(Position Q =P->Next;Q->Next!=NULL;Q=Q->Next){
if
(Q->Next->Element < min){
min = Q->Next->Element;
curMin = Q;
}
}

curMin->Next->Element=P->Next->Element;
P->Next->Element = min;
}
}

int
main(){
List L;
MakeNullList(L);
InsertList(3,1,L);
InsertList(4,1,L);
InsertList(2,2,L);
InsertList(5,3,L);
InsertList(6,2,L);
InsertList(7,1,L);
InsertList(8,2,L);

PrintList(L);
DeleteList(2,L);
DeleteList(5,L);
printf("Retrieve(3,L) = %d\n",Retrieve(3,L));
printf("Locate(100,L) = %d\n",Locate(100,L));
ReverseList(L);
printf("Danh sach dao:\n");
PrintList(L);
SortList(L);
printf("Danh sach sau khi sap xep:\n");
PrintList(L);

return
0;
}


Bài liên quan

Bài liên quan