//411440281 Lu-Wei-Yi
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
struct stack {
int A[SIZE];
int top;
};
int empty(struct stack *ps){
return(ps->top==-1);
}
int full(struct stack *ps){
return(ps->top==SIZE-1);
}
int push(struct stack *ps,int data){
if(full(ps)){
printf("stack is full");
exit(0);
}
ps->A[++ps->top]=data;
}
int pop(struct stack *ps){
if(empty(ps)){
printf("stack is empty");
exit(1);
}
return ps->A[ps->top--];
}
//411440281 Lu-Wei-Yi
int main(){
struct stack stack_1; //主要使用的堆疊
struct stack stack_2; //存取pop出數字的堆疊
stack_1.top=-1;
stack_2.top=-1;
int k; //要找的第 k 個數字
//-------build the random number--------------------------------//
srand(time(NULL));
int i;
printf("Generate 10 numbers into the stack , and print them");
for (i = 0; i < 10; ++i) {
push(&stack_1,rand() % 10 + 1);
printf("\n%d", stack_1.A[i]);
}
printf(" <- top\n\n");
//-------assign integer k the 2nd element----------------------//
k=pop(&stack_1); //從stack_1 pop數字出來後 放到stack_2
push(&stack_2,k);
if(empty(&stack_1)){
printf("1-element stack\n");
exit(2);
}
k=pop(&stack_1);
push(&stack_2,k);
printf("QStion1 : k = %d \n",k);
while(!empty(&stack_2)){
push(&stack_1,pop(&stack_2));
}
//411440281 Lu-Wei-Yi
//-------assign integer k the 9th element----------------------//
k=pop(&stack_1);
push(&stack_2,k);
int j;
for(j=1;j<=8;j++){
if(empty(&stack_1)){
printf("element is empty in %d\n",j);
exit(3);
}
k=pop(&stack_1);
push(&stack_2,k);
}
printf("QStion2 : k = %d \n",k);
while(!empty(&stack_2)){
push(&stack_1,pop(&stack_2));
}
//-------assign integer k the bottom element----------------------//
k=0;
k=pop(&stack_1);
push(&stack_2,k);
while(!empty(&stack_1)){
k=pop(&stack_1);
push(&stack_2,k);
}
printf("QStion3 : k = %d \n",k);
while(!empty(&stack_2)){
push(&stack_1,pop(&stack_2));
}
//411440281 LU-WEI-YI
//-------assign integer k the 2nd element from top----------------------//
int bottom;
k=0;
k=pop(&stack_1);
push(&stack_2,k);
if(empty(&stack_1)){
printf("1-element stack\n");
exit(4);
}
while(!empty(&stack_1)){
k=bottom;
bottom=pop(&stack_1);
push(&stack_2,bottom);
}
printf("QStion4 : k = %d \n",k);
while(!empty(&stack_2)){
push(&stack_1,pop(&stack_2));
}
//411440281 LU-WEI-YI
//-------printout all the the element in stack---------------------//
printf("QStion5 : ");
k=pop(&stack_1);
push(&stack_2,k);
printf("%d <-top \n",k);
while(!empty(&stack_1)){
k=pop(&stack_1);
push(&stack_2,k);
printf(" %d\n",k);
}
return 0;
}
//411440281 Lu-Wei-Yi
To embed this project on your website, copy the following code and paste it into your website's HTML: