Data structure - basic operations of chain stack (C++)


Preface

This article mainly introduces the basic operations of chain stack in data structure


1. Definition of chain stack

typedef struct Stack
{
    
    
	struct Stack* next;
	int data;
}Stack,*LinkStack;

2. Initialization of the stack

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

3. Determine whether the stack is empty

//判断栈是否为空 为空返回1 不为空返回0
int is_Empty_Stack(LinkStack S)
{
    
    
	if (!S)
	{
    
    
		return 1;
	}	
	return 0;
}

4. Access the top element of the stack

//取栈顶元素
void Gettop(LinkStack S,int &e)
{
    
    
	if (S == NULL)
	{
    
    
		cout << "该栈为空" << endl;
		return;
	}
	e = S->data;
}

5. Push into the stack

//入栈操作
void Push_Stack(LinkStack& S, int e)
{
    
    
	LinkStack p = new Stack;
	if (!p)
	{
    
    
		cout << "申请空间失败" << endl;
	}
	p->data = e;
	p->next = S;
	S = p;
}

6. Get out of the stack

//出栈操作
void Pop_Stack(LinkStack &S, int& e)
{
    
    
	if (S == NULL)
	{
    
    
		cout << "该栈为空" << endl;
		return;
	}
	e = S->data;
	LinkStack p = S;
	S = S->next;
	delete p;
}

7. Clear the stack

//清空栈
void Clear_Stack(LinkStack S)
{
    
    
	S = NULL;
}

8. Destroy the stack

//销毁栈
void Destory_Stack(LinkStack S)
{
    
    
	while (S != NULL)
	{
    
    
		LinkStack temp = S;
		S = S->next;
		delete temp;
	}
}

9. All source codes

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
typedef struct Stack
{
    
    
	struct Stack* next;
	int data;
}Stack,*LinkStack;
//初始化栈
void Init_Stack(LinkStack& S)
{
    
    
	S = NULL;
}
//判断栈是否为空 为空返回1 不为空返回0
int is_Empty_Stack(LinkStack S)
{
    
    
	if (!S)
	{
    
    
		return 1;
	}	
	return 0;
}
//入栈操作
void Push_Stack(LinkStack& S, int e)
{
    
    
	LinkStack p = new Stack;
	if (!p)
	{
    
    
		cout << "申请空间失败" << endl;
	}
	p->data = e;
	p->next = S;
	S = p;
}
//出栈操作
void Pop_Stack(LinkStack &S, int& e)
{
    
    
	if (S == NULL)
	{
    
    
		cout << "该栈为空" << endl;
		return;
	}
	e = S->data;
	LinkStack p = S;
	S = S->next;
	delete p;
}
//取栈顶元素
void Gettop(LinkStack S,int &e)
{
    
    
	if (S == NULL)
	{
    
    
		cout << "该栈为空" << endl;
		return;
	}
	e = S->data;
}
//清空栈
void Clear_Stack(LinkStack S)
{
    
    
	S = NULL;
}
//销毁栈
void Destory_Stack(LinkStack S)
{
    
    
	while (S != NULL)
	{
    
    
		LinkStack temp = S;
		S = S->next;
		delete temp;
	}
}
int main()
{
    
    
	LinkStack S;
	Init_Stack(S);
	is_Empty_Stack(S);
	int e = 0;

	Push_Stack(S, 2);
	
	Pop_Stack(S, e);

	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_63614711/article/details/127983172