C++数据结构链栈的初始化、元素进栈、出栈、判断是否为空

mac2024-12-20  6

初始化等操作链栈的学习记录

#include <stdio.h> #include <stdlib.h> #include "stdafx.h" #include "iostream" using namespace std; #define OK 1 #define ERROR 0 typedef char SElemType; //栈的链式储存结构 typedef struct SNode { SElemType data; //数据域 struct SNode *next; //指针域 }SNODE, *PSNODE; //栈顶节点 typedef struct { PSNODE top; //栈顶指针 int count; //栈的长度 }LinkStack; //初始化栈顶节点 int initStack(LinkStack *s) { s->top = (PSNODE)malloc(sizeof(SNODE)); if (!s->top) return ERROR; s->top = NULL; s->count = 0; cout << "初始化链栈成功" << endl; return OK; } //判断栈是否为空 int isStackEmpty(LinkStack *s) { if (s->top == NULL) { return OK; } else { return ERROR; } } //输出顺序为出栈的顺序 int stackTraverse(LinkStack *s) { int i; if (isStackEmpty(s) == OK) return ERROR; PSNODE p = s->top; for (i = s->count; i>0; i--) { cout << p->data << endl; p = p->next; } return OK; } //链栈元素入栈 int Push_LS(LinkStack *s, SElemType e) { PSNODE p = (PSNODE)malloc(sizeof(SNODE)); if (!p) return ERROR; p->data = e; p->next = s->top; //新结点指向栈顶指针指向的地址 s->top = p; //更新栈顶指针 s->count++; // 节点增加1 return OK; } // 获取栈顶元素 int GetTop(LinkStack *s, SElemType *e) { if (isStackEmpty(s) == OK) return ERROR; *e = s->top->data; return OK; } //链栈元素出栈 int Pop_LS(LinkStack *s, SElemType *e) { if (isStackEmpty(s) == OK) return ERROR; PSNODE temp = s->top; *e = temp->data; s->top = temp->next; s->count--; free(temp); return OK; } //销毁栈 int clearStack(LinkStack *s) { PSNODE p, q = NULL; if (isStackEmpty(s) == OK) return ERROR; p = s->top; for (int i = s->count; i > 0; i--) { q = p->next; free(p); p = q; } s->count = 0; cout << "释放栈成功" << endl; return OK; } int main() { bool tagbool; LinkStack s, *ls; SElemType a, *e; e = (SElemType*)malloc(sizeof(SElemType)); ls = &s; //(1)初始化栈 initStack(ls); int n; //(2)判断栈s是否为空 tagbool = isStackEmpty(ls); cout << "判断栈是否为空" << tagbool << endl; //(3)以此进栈元素 cout << "插入元素abcde" << endl; Push_LS(ls, 'a'); Push_LS(ls, 'b'); Push_LS(ls, 'c'); Push_LS(ls, 'd'); Push_LS(ls, 'e'); //(4)判断栈s是否为空 tagbool = isStackEmpty(ls); cout << "判断栈是否为空" << tagbool << endl; //(5)输出出栈序列 cout << "输出出栈序列" << endl; stackTraverse(ls); //(6)判断栈s是否为空 tagbool = isStackEmpty(ls); cout << "判断栈是否为空" << tagbool << endl; //(7)释放栈 clearStack(ls); return 0; }

 

最新回复(0)