标签:next 链接 输出 项目结构 event lib har open null
项目结构:
main.cpp:
#include <iostream> #include<stdio.h> #include<stdlib.h> #include "function_for_LinkStack.h" using namespace std; int main() { TestLinkStack(); return 0; }
function_for_LinkStack.h:
#ifndef FUNCTION_FOR_LINKSTACK_H_INCLUDED #define FUNCTION_FOR_LINKSTACK_H_INCLUDED /* 链栈是运算受限的单链表,只能在链表头部进行操作 链表的头指针就是栈顶 不需要头节点 基本不存在栈满的情况 空栈 相当于 头指针指向空 插入和删除仅在栈顶出执行 节点之间的链接方向:(头节点)栈顶->栈底 */ typedef char ElemType; typedef struct StackNode{ ElemType data; //数据域 struct StackNode *next; //指针域 }StackNode, *LinkStack; //初始化链栈 void InitStack(LinkStack &S); //判空 int StackEmpty(LinkStack S); //入栈 void Push(LinkStack &S, ElemType e); //出栈 void Pop(LinkStack &S); //出栈并获取栈顶元素 ElemType Pop_with_elem(LinkStack &S); //获取栈顶元素 ElemType GetTop(LinkStack &S); //打印栈中元素(自顶向下) void PrintStack(LinkStack S); //测试 void TestLinkStack(); #endif // FUNCTION_FOR_LINKSTACK_H_INCLUDED
function_for_LinkStack.cpp:
#include<stdio.h> #include<stdlib.h> #include "function_for_LinkStack.h" //初始化链栈 void InitStack(LinkStack &S){ //构造一个空栈,栈顶指针置空 S=NULL; } //判空 int StackEmpty(LinkStack S){ if(S == NULL){ return 1; }else{ return 0; } } //入栈 void Push(LinkStack &S, ElemType e){ LinkStack p = (LinkStack)malloc(sizeof(StackNode)); //生成新节点 p->data = e; //数据域置为e p->next = S; //将新节点插入栈顶 S=p; //修改栈顶指针 } //出栈 void Pop(LinkStack &S){ //先判断栈是否为空 if(S == NULL){ exit(0); } LinkStack p = S; //声明新节点指向栈顶 S = S->next; free(p); //释放临时节点 } //出栈并获取栈顶元素 ElemType Pop_with_elem(LinkStack &S){ ElemType e; //存放栈顶元素的数据域 //先判断栈是否为空 if(S != NULL){ exit(0); } LinkStack p = S; //声明新节点指向栈顶 S = S->next; e = p->data; free(p); //释放临时节点 return e; //返回数据域类型 } //获取栈顶元素 ElemType GetTop(LinkStack &S){ if(S != NULL){ return S->data; } } //打印栈中元素(自顶向下) void PrintStack(LinkStack S){ LinkStack p = S; //声明指向栈顶的指针 while(p != NULL){ printf("%c ", p->data); //依次输出每个节点的数据域 p = p->next; } } //测试 void TestLinkStack(){ LinkStack S; //声明栈顶节点 printf("初始化:\n"); InitStack(S); //入栈 printf("压入元素:\n"); Push(S, ‘a‘); Push(S, ‘b‘); Push(S, ‘c‘); Push(S, ‘d‘); Push(S, ‘e‘); printf("\n获取栈顶元素:%c\n", GetTop(S)); printf("\n栈是否为空?%d\n", StackEmpty(S)); printf("\n打印栈:\n"); PrintStack(S); printf("\n出栈:\n"); Pop(S); printf("\n获取栈顶元素:%c\n", GetTop(S)); printf("\n栈是否为空?%d\n", StackEmpty(S)); printf("\n打印栈:\n"); PrintStack(S); printf("\n再压入新元素:\n"); Push(S, ‘f‘); printf("\n栈是否为空?%d\n", StackEmpty(S)); printf("\n打印栈:\n"); PrintStack(S); printf("\n获取栈顶元素:%c\n", GetTop(S)); }
运行结果:
标签:next 链接 输出 项目结构 event lib har open null
原文地址:https://www.cnblogs.com/CPU-Easy/p/11722036.html