C-like language-the basic operation of the chain stack: initialization, determine whether it is empty, into the stack, out of the stack, take the top element of the chain stack

Code that can run normally, complete and accurate C-like language

Introduction

Chain stack: The operation is a restricted single linked list. The chained storage result of the stack can only be operated at the head of the linked list (top of the stack), so there is no need to add a head node. The top pointer on the stack
is the last pointer The LIFO structure of the linear table is
empty. The stack without any elements is called the empty stack.

Code area

#include<stdio.h>
#include<stdlib.h>
typedef int SElemType;
typedef struct StackNode
{
 SElemType data;   //数据域
 struct StackNode *next;   //指针域
}StackNode,*LinkStack;

enum Status{ERROR,OK};   //定义枚举类型,此处也可换为布尔类型的TRUE,FALSE

//链栈初始化
Status InitStack(LinkStack &S)
{
 S=NULL;  //S为空指针; 区分野指针:没有任何值指向,野指针是不允许的
 return OK;
}

//判断链栈是否为空
Status StackEmpty(LinkStack S)
{
 if(S==NULL)  //top=NULL也可
 return OK;
 else
 return ERROR;
}

//链栈进栈--压栈--就是插入的操作
Status Push(LinkStack &S,SElemType e)
{
 LinkStack p=new StackNode;  //生成新结点p
 if(!p)
 return ERROR;
 p->data=e;  //没有链栈满不满这一说法,因为链栈不是连续的
 p->next=S;
 S=p;
}

//链栈出栈--弹栈--删除的操作
Status Pop(LinkStack &S,SElemType &e)
{
LinkStack p;
 if(S==NULL)  
 return ERROR;   //栈空
 e=S->data;
 p=S;
 S=S->next;
 delete p;   //释放p空间。注意:delete 与new  对应使用;free与malloc对应使用
 return OK;
}

//取链栈栈顶元素
SElemType GetTop(LinkStack S)
{
if(S=NULL)
return ERROR;
else
return S->data;
}

int main()
{
    LinkStack S;
	SElemType e;
	int n,a;
	InitStack(S);   //初始化

	printf("input the number you want to push\n");   //输入进栈的元素个数
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&e);   //依次输入元素
		Push(S,e);    //入栈
	}
	
	a=GetTop(S);  //取栈顶元素
    printf("the element of top is %d\n",a);

    printf("now,look at all these elements\n");
	while(!StackEmpty(S))   //若栈非空
	{
		Pop(S,e);   //出栈
		printf("%d  ",e);
	}

    
	return 0;
}
Published 57 original articles · Liked 54 · Visits 2358

Guess you like

Origin blog.csdn.net/September_C/article/details/104937098
Recommended