C语言实现链栈的初始化&进栈&出栈&读取栈顶元素

版权声明:作者:TC125 若无特殊说明,所发博文皆为原创,转载请务必注明出处、保留原文地址。欢迎交流分享! https://blog.csdn.net/TC125/article/details/84591753
/*链表实现栈的一系列操作*/
 
#include<stdio.h>
#include<stdlib.h> 

#define OK 1
#define ERROR 0

typedef struct node
{
	int data;
	struct node *next;
}LinkStackNode,*LinkStack;

/**********************各个子函数的定义*********************/
void initStack(LinkStack *top);       //初始化链栈 
int push(LinkStack top,int n);        //链栈进栈操作 
void pop(LinkStack top);              //链栈出栈操作 
int getTop(LinkStack top,int *s);     //读取链栈栈顶元素 

int main()
{
	LinkStack top;
	int choice;
	while(true)
	{
        printf("*****************Please enter your choice*****************\n\n");
        printf("                choice 1:Stack initialization\n");
        printf("                choice 2:Into the stack\n");
        printf("                choice 3:Out of the stack\n");
        printf("                choice 4:Read the stack elements\n");
        printf("                choice 0:exit\n\n");
	 	scanf("%d",&choice);
		switch(choice)
		{
			case 1:
				initStack(&top);
				break;
			case 2:
				int n;
				printf("Please enter the number into the stack elements:");
				scanf("%d",&n);
				(push(top,n)==1)?printf("%d个元素依次进栈成功\n",n):printf("%d个元素依次进栈失败\n",n);	
				break;
			case 3:
				pop(top);
				break;
			case 4:
				int* s;
				(getTop(top,s)==1)? printf("栈顶元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目运算符
				break;		
			case 0:
				exit(0);
				break;
			default:
				printf("ERROR!!\n");
				exit(0);
				break;
		}
	}
	return 0;
}

/**********************各个子函数功能的实现*********************/
void initStack(LinkStack *top)
{   //初始化 
	*top=(LinkStack)malloc(sizeof(LinkStackNode));  //带头结点的单链表 
	(*top)->next=NULL; 
} 
 
int push(LinkStack top,int n)	//进栈 ,将元素压入栈中 
{		
	LinkStackNode *temp;
	int n1,n2;
	printf("Please enter into the stack elements in turn:\n");  
	for(n1=0;n1<n;n1++)
	{
		scanf("%d",&n2);
		temp=(LinkStackNode *)malloc(sizeof(LinkStackNode));  //结点申请空间 
		if(temp==NULL) return ERROR;  //申请空间失败
		temp->data=n2;
		temp->next=top->next;          //采用头插法存储元素 
		top->next=temp; 
	}
	return OK;
}

void pop(LinkStack top)          //栈顶元素出栈 
{           
	int a;
	LinkStackNode *temp;
	if(top->next==NULL)
	{               //栈为空,出栈失败 
		printf("An empty stack error!!!!\n");
	}
	else
	{
		temp=top->next;
		a=temp->data;
		top->next=temp->next;
		free(temp);
		printf("栈顶元素%d出栈成功.\n",a);  
	}  
}

int getTop(LinkStack top,int *s)        //获读取栈顶元素 
{    
	if(top->next==NULL)              //栈为空,读取栈顶元素失败 
	{ 
		return ERROR;
	}
	else
	{
		*s=(top->next)->data;           //读取栈顶元素,不出栈 
		return OK;
	}
}

猜你喜欢

转载自blog.csdn.net/TC125/article/details/84591753