栈
#include <stdio.h>
#include <malloc.h>
#define MAX_SIZE 100
typedef int elemType;
typedef struct SNode *stack;
struct SNode{
elemType data[MAX_SIZE];
int top;
};
stack S;
stack createStack();
int isFull(stack S);
int isEmpty(stack S);
void push(stack S,elemType x); //入栈
elemType pop(stack S); //出栈
stack createStack()
{
S = (stack)malloc(sizeof(struct SNode));
S->top = -1;
return S;
}
int isFull(stack S)
{
return (S->top == MAX_SIZE-1);
};
int isEmpty(stack S)
{
return (S->top == -1);
};
void push(stack S,elemType x)
{
if(isFull(S)){
printf("Stack is full\n");
return;
}else{
S->top++;
S->data[S->top] = x;
return;
}
};
elemType pop(stack S)
{
if(isEmpty(S)){
printf("Stack is empty\n");
return 0;
}else{
elemType value = S->data[S->top];
S->top--;
return value;
}
};
int main()
{
S = createStack();
printf("5 enter\n");
push(S,5);
printf("6 enter\n");
push(S,6);
printf("8 enter\n");
push(S,8);
printf("12 enter\n");
push(S,9);
printf("345 enter\n");
push(S,345);
printf("23 enter\n");
push(S,23);
while(!isEmpty(S)){
printf("Pop %d\n",pop(S));
}
return 0;
}
//5 enter
//6 enter
//8 enter
//12 enter
//345 enter
//23 enter
//Pop 23
//Pop 345
//Pop 9
//Pop 8
//Pop 6
//Pop 5
链栈
#include <stdio.h>
#include <malloc.h>
typedef int elemType;
typedef struct SNode *stack;
struct SNode{
elemType data;
stack next;
};
stack createStack();
int isEmpty(stack S);
void push(stack S,elemType x);
elemType pop(stack S);
stack createStack()
{
stack S;
S = (stack)malloc(sizeof(struct SNode));
S->next = NULL;
return S;
};
int isEmpty(stack S)
{
return (S->next == NULL);
};
void push(stack S,elemType x)
{
stack temp;
temp = (stack)malloc(sizeof(struct SNode));
temp->data = x;
temp->next = S->next;
S->next = temp; //接在s的后面
};
elemType pop(stack S)
{
stack temp;
elemType value;
if(isEmpty(S)){
printf("Stack is Empty");
return 0;
}else{
temp = S->next; //出栈第一个元素在栈顶元素后
S->next = temp->next;
value = temp->data;
free(temp);
return value;
}
};
int main()
{
stack S;
S = createStack();
printf("Enter 5\n");
push(S,5);
printf("Enter 21\n");
push(S,21);
printf("Enter 23\n");
push(S,23);
printf("Enter 4\n");
push(S,4);
printf("Enter 2\n");
push(S,2);
while(!isEmpty(S)){
printf("pop %d\n",pop(S));
}
}
//Enter 5
//Enter 21
//Enter 23
//Enter 4
//Enter 2
//pop 2
//pop 4
//pop 23
//pop 21
//pop 5