栈是仅在表尾进行插入、删除操作的线性表。即栈 S= (a1, a2, a3, ………,an-1, an),其中表尾称为栈顶 /top,表头称为栈底/base。
由于只能在表尾进行操作,因此栈的运算规则就是“后进先出”(LIFO)
和线性表类似,栈也有两种存储结构——顺序栈与链栈
1.顺序栈的C语言实现#include
#include
typedef struct Stack {
int *data;//数据域
int size;//栈长度,也是栈顶数组下标-1
int max;//栈最大容量
} Stack;
//初始化
Stack *initStack(int max)
{
struct Stack *stack;
stack = (struct Stack *)malloc(sizeof(struct Stack));
stack->size = 0;
stack->max = max;
stack->data = (int*)malloc(sizeof(int)*max);
return stack;
}
//压栈
void push(Stack *stack, int item)
{
if (stack->size >= stack->max)
{
printf("stack is full! \n");
}else{
stack->data[stack->size++] = item;
}
}
//出栈
int pop(Stack *stack)
{
if (stack->size >= 0)
{
return stack->data[--stack->size];
}
}
//test
int main()
{
struct Stack *stack;
stack = initStack(3);
push(stack,1);
push(stack,2);
push(stack,3);
push(stack,4);
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
push(stack,5);
push(stack,6);
push(stack,7);
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
return 0;
}
测试效果:
2.链栈的C语言实现
本想偷懒,算了,还是写一遍吧,区别只是用链表去代替了数组,其实还不如数组方便省事一。一,但是可以无限长,,,#include
#include
typedef struct StackNode {
int data;//数据域
struct StackNode *next;//指针域,这里用next或者pre都行,看怎么规定左右了,如果是左进左出那就是next,右进右出就是pre好理解
} StackNode;
typedef struct LinkedStack {
int size;//栈长度
int max;//栈最大容量
struct StackNode *top;//指针域
} LinkedStack;
//初始化
LinkedStack *initStack(int max)
{
struct LinkedStack *stack;
stack = (struct LinkedStack *)malloc(sizeof(struct LinkedStack));
stack->size = 0;
stack->max = max;
stack->top = NULL;
return stack;
}
//压栈
void push(LinkedStack *stack, int item)
{
if (stack->size >= stack->max)
{
printf("stack is full! \n");
}else{
struct StackNode *node;
node = (struct StackNode *)malloc(sizeof(struct StackNode));
node->data = item;
node->next = stack->top;
stack->size++;
stack->top = node;
}
}
//出栈
int pop(LinkedStack *stack)
{
if (stack->size > 0)
{
struct StackNode *top;
top = stack->top;
stack->top = top->next;
stack->size--;
return top->data;
}
}
int main()
{
struct LinkedStack *stack;
stack = initStack(3);
push(stack,1);
push(stack,2);
push(stack,3);
push(stack,4);
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
push(stack,5);
push(stack,6);
push(stack,7);
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
printf("stack out:%d \n", pop(stack));
return 0;
}