顺序表的栈的实现,简单的实现功能为入栈和出栈功能:
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
}STACK;
void initStack(STACK *s)
{
s->top = -1;
}
int push(STACK *s, ElemType x)
{
if(s->top == MaxSize - 1)
{
printf("\n stack is full");
return 0;
}
s->top++;
s->data[s->top] = x;
return 1;
}
int Empty(STACK *s)
{
return (s->top == -1 ? 1 : 0);
}
int pop(STACK *s , ElemType *x)
{
if(Empty(s))
{
printf("\n stack is free");
return 0;
}
*x = s->data[s->top];
s->top--;
return 1;
}
int getTop(STACK *s, ElemType *x)
{
if(Empty(s))
{
printf("\n stack is free");
return 0;
}
*x = s->data[s->top];
return 1;
}
int main()
{
STACK s;
ElemType x;
initStack(&s);
push(&s, 10);
getTop(&s, &x);
printf("%4d\n", x);
push(&s, 25);
getTop(&s, &x);
printf("%4d\n", x);
pop(&s, &x);
getTop(&s, &x);
printf("%4d\n", x);
system("pause");
return 0;
}
链表的栈实现:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct snode{
ElemType data;
struct snode *next;
}LinkSTACK;
LinkSTACK *top;
void initStack(LinkSTACK **top)
{
*top = (LinkSTACK*)malloc(sizeof(LinkSTACK));
(*top)->next = NULL;
}
int push(LinkSTACK **top, ElemType x)
{
LinkSTACK *s;
s = (LinkSTACK*)malloc(sizeof(LinkSTACK));
s->data = x;
s->next = (*top)->next;
(*top)->next = s;
return 1;
}
int Empty(LinkSTACK **top)
{
return ((*top)->next == NULL ? 1 : 0);
}
int pop(LinkSTACK **top, ElemType *x)
{
LinkSTACK *s;
if(Empty(top))
{
printf("\n stack is free");
return 0;
}
s = (*top)->next;
*x = (*top)->data;
(*top)->next = s->next;
free(s);
return 1;
}
int getTop(LinkSTACK **top, ElemType *x)
{
if(Empty(top))
{
printf("\n stack is free");
return 0;
}
*x = (*top)->next->data;
return 1;
}
int main()
{
ElemType x;
initStack(&top);
push(&top, 15);
getTop(&top, &x);
printf("%d\n", x);
push(&top, 20);
push(&top, 30);
getTop(&top, &x);
printf("%d\n", x);
pop(&top, &x);
getTop(&top, &x);
printf("%d\n", x);
system("pause");
return 0;
}