CÀI ĐẶT STACK BẰNG MẢNG
Code:
#include "conio.h"
#include "stdio.h"
#define MaxLength 100
#define Null -1
typedef int ElementType;
typedef struct {
ElementType Elements[MaxLength];
unsigned int Top_idx;
} Stack;
//khoi tao ngan xep rong
Stack MakeNull_Stack() {
Stack temp;
temp.Top_idx = 0;
return temp;
}
//kiem tra ngan xep rong
char Empty_Stack(Stack S){
return S.Top_idx==0;
}
//kiem tra ngan xep day
char Full_Stack(Stack S){
return S.Top_idx==MaxLength;
}
//lay noi dung phan tu o dinh ngan xep
ElementType Top(Stack S){
if (!Empty_Stack(S))
return S.Elements[S.Top_idx-1];
else {
printf("Loi! Ngan xep rong");
return Null;
}
}
//day 1 phan tu ra khoi ngan xep
void Pop(Stack *S){
if (!Empty_Stack(*S))
S->Top_idx--;
else
printf("Loi! Ngan xep rong!");
}
//them 1 phan tu vao dau ngan xep
void Push(ElementType X, Stack *S){
if (Full_Stack(*S))
printf("Loi! Ngan xep day!");
else{
S->Elements[S->Top_idx]=X;
S->Top_idx++;
}
}
//xuat ngan xep
void Out_Stack(Stack S) {
Stack temp = S;
while(!Empty_Stack(temp)) {
printf("%d\t",Top(temp));
Pop(&temp);
}
}
//nhap vao ngan xep
Stack Input_Stack(unsigned int n) {
Stack S = MakeNull_Stack();
ElementType x;
for(int i = 0; i<n; i++) {
printf("Nhap phan tu %d :",i);
scanf("%d",&x);
Push(x,&S);
}
return S;
}
void main() {
clrscr();
unsigned int n;
printf("Nhap vao n = ");
scanf("%d",&n);
Stack S = Input_Stack(n);
printf("Ngan xep vua nhap:\n");
Out_Stack(S);
getch();
}