[Data structure] chain stack (without head node)

#include<stdio.h>
#include<stdlib.h>
typedef struct SNode{
    
    
	int data;
	struct SNode *next;
}*LinkStack,SNode; 

//初始化栈 
void InitStack(LinkStack &S){
    
    
	S=NULL;
}

//入栈
void Push(LinkStack &S,int x){
    
    
	SNode *p=(SNode*)malloc(sizeof(SNode));
	p->data=x;
	p->next=S;  //出错 
	S=p;
} 

//出栈 
bool Pop(LinkStack &S,int &x){
    
    
	if(S==NULL)  return false;
	SNode *p=S->next;
	x=S->data;
	free(S);
	S=p;
	return true;
}

//读取栈顶元素
int GetTop(LinkStack S){
    
    
	if(S!=NULL)
		return S->data;
} 

//打印栈
PrintStack(LinkStack S){
    
    
	while(S!=NULL){
    
    
		printf("%d ",S->data);
		S=S->next;
	}
	printf("\n");
} 

int main(){
    
    
	LinkStack s;
	InitStack(s);
	for(int i=0;i<5;i++)
		Push(s,i);
	printf("%d\n",GetTop(s));
	PrintStack(s);
	int x;
	Pop(s,x);
	printf("%d\n",x);
	PrintStack(s);

	return 0;	
	
}

Guess you like

Origin blog.csdn.net/mossfan/article/details/115935355