Ngăn Xếp Stack - Kiểu cài 2: cài tựa danh sách liên kết
#include <stdio.h>
#include <malloc.h>
typedef int ElementType;
typedef struct Node{
ElementType Element;
Node* Next;
};
typedef Node* Position;
typedef Position Stack;
void MakeNullStack(Stack &S){
S =(Node*)malloc(sizeof(Node));
S->Next = NULL;
}
int EmptyStack(Stack S){
return (S->Next==NULL);
}
void Push(ElementType X, Stack &S){
Node* T = (Node*)malloc(sizeof(Node));
T->Element = X;
T->Next = S->Next;
S->Next = T;
}
void Pop(Stack &S){
Position P = S->Next;
S->Next=P->Next;
free(P);
}
ElementType Peek(Stack S){
return S->Next->Element;
}
void NhiPhan(int n){
Stack S;
MakeNullStack(S);
while(n!=0){
int sodu = n % 2;
Push(sodu,S);
n = n / 2;
}
while(!EmptyStack(S)){
printf("%d",Peek(S));
Pop(S);
}
printf("\n");
}
int main(){
int n;
printf("Nhap so nguyen n = ");
scanf("%d",&n);
for(int i=2;i<=n;i++){
printf("%d = ",i);
NhiPhan(i);
}
return 0;
}