欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈的C语言实现

程序员文章站 2022-05-26 19:42:14
...

使用整型数组sta[SIZE]和整型变量top构成的结构体实现栈

栈的操作通过结构体指针实现

有如下功能:

1.栈空判断(isEmpty)

2.看栈顶(peek)

3.入栈(push)

4.出栈(pop)

5.销毁栈(destroy)

程序实现如下:

#include<stdio.h>
#include<string.h>//memset在其中

#define SIZE 10

struct stack
{
    int sta[SIZE];
	int top;
};

void init_stack(struct stack *s)//初始化栈
{
    memset(s->sta, 0, sizeof(s->sta)); 
	//memset为memory set 缩写,直接操作内存空间,memset(*p,int c,int n)意为将p所指的前n个字节的内存单元都用c填充
	s->top = -1; //空栈时栈顶为-1
}

int isEmpty(struct stack *s)//判断栈空
{
	if ((s->top) == -1)
		return 1;
	else
		return 0;
}

int peek(struct stack*s)//看栈顶
{
	if (isEmpty(s))
	{	
		printf("Stack is Empty!\n");
		return -1;
	}
	else 
		return ((s->sta)[s->top]);
}

int push(struct stack *s, int data)//入栈
{
	if(s->top == SIZE)
	{
		printf("The stack is full.\n");
		return 1;
	}
	(s->top)++;
	s->sta[s->top] = data;
	return 0;
} 

int pop(struct stack *s)//出栈
{
	int tmp;
	if(s->top == -1)
	{
		printf("The stack is empty.\n");
		return -1;
	}
	else
	{
		tmp = (s->sta)[s->top];
		(s->top)--;
		return tmp;
	}
}

void destroy(struct stack *s)//销毁栈
{
	s->top = -1;
	memset(s->sta,0,sizeof(s->sta));
}

void main()
{
	struct stack mystack;
    struct stack *p;
	int i;
	
	p = &mystack;

	init_stack(p);
    for(i = 0; i<=9; i++)
	{
		push(p,i);
		printf("%d已入栈\n",i);
	}

	printf("using peek get the number which in top is %d\n",peek(p));
	/*测试pop
	for(i = 0; i<=8; i++)
	{
		printf("%d already out\n",pop(p));
	}
    printf("using peek get the number which in top is %d\n",peek(p));
	printf("%d already out\n",pop(p));*/
    /*测试destroy
	destroy(p);
	printf("using peek get the number which in top is %d\n",peek(p));*/
	if (isEmpty(p))
	    printf("Stack is Empty!\n");
    else
		printf("NO,Stack isn't empty\n");
}

运行结果:

栈的C语言实现