用链表的方式实现栈
//栈结构体:
typedef struct stack
{
int value; //存放数据
struct stack *next; //指向下一个节点
}STACK_LIST;
//建立空栈,确定head节点
STACK_LIST *CreateNewStack();
//判断栈是否为空
bool IsEmptyStack(STACK_LIST *head);
//入栈
void PushStack(STACK_LIST *head, int elem);
//出栈
void PopStack(STACK_LIST *head);
//获取栈顶元素
STACK_LIST *GetTopElem(STACK_LIST *head);
//获取栈元素个数
int GetTotalNum(STACK_LIST *head);
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
using std::cout;
using std::endl;
typedef struct stack
{
int value;
struct stack *next;
}STACK_LIST;
//建立空栈,确定head节点
STACK_LIST *CreateNewStack()
{
STACK_LIST *head = (STACK_LIST *)malloc(sizeof(STACK_LIST));
head->next = NULL;
head->value = -1;
return head;
}
bool IsEmptyStack(STACK_LIST *head)
{
if(head->next == NULL)
return true;
return false;
}
//入栈
void PushStack(STACK_LIST *head, int elem)
{
cout<<"push stack:"<<elem<<endl;
STACK_LIST *p = (STACK_LIST *)malloc(sizeof(STACK_LIST));
p->next = head->next;
head->next = p;
p->value = elem;
}
//出栈
void PopStack(STACK_LIST *head)
{
if(IsEmptyStack(head))
{
cout<<"stack is empty!"<<endl;
return;
}
STACK_LIST *p = head->next;
cout<<"pop stack:"<<p->value<<endl;
head->next = p->next;
free(p);
}
//获取栈顶元素
STACK_LIST *GetTopElem(STACK_LIST *head)
{
if(IsEmptyStack(head))
{
cout<<"stack is empty!"<<endl;
return NULL;
}
return head->next;
}
//获取栈元素个数
int GetTotalNum(STACK_LIST *head)
{
if(IsEmptyStack(head))
{
cout<<"stack is empty!"<<endl;
return 0;
}
int count = 0;
STACK_LIST *p = head;
while(p->next != NULL)
{
p = p->next;
count++;
}
return count;
}
int main()
{
STACK_LIST *head = CreateNewStack();
PushStack(head,10);
PushStack(head,20);
PushStack(head,30);
cout<<"total num elem:"<<GetTotalNum(head)<<endl;
STACK_LIST *p = GetTopElem(head);
cout<<"top elem:"<<p->value<<endl;
PopStack(head);
PopStack(head);
PopStack(head);
cout<<"total num elem:"<<GetTotalNum(head)<<endl;
return 0;
}
打印结果:
push stack:10
push stack:20
push stack:30
total num elem:3
top elem:30
pop stack:30
pop stack:20
pop stack:10
stack is empty!
total num elem:0
参考:
https://www.cnblogs.com/zhang01010/p/7749342.html