来源:互联网 发布:淘宝店铺装修模版下载 编辑:程序博客网 时间:2024/06/07 05:30

栈是一种数据结构,在计算机科学中被广泛使用。今天刚刚上了数据结构课,晚上就顺便写了一个比较简单的栈。

栈的特性在百度百科还有维基百科都有提到。其它菊苣的博客里面也有详细阐述,就不再赘述了。

直接把我写的栈贴出来。希望大家能够一起进步!

#include <iostream>using namespace std;typedef int Element;typedef struct Stack {Element data;Stack *next;}node;node *initStack() {node *top = new node;if (top == NULL) {cout << "分配内存失败!请检查程序!" << endl;exit(-1);}top -> data = -1;top -> next = NULL;cout << "创建栈成功!" << endl;return top;}bool isEmpty(node *top) {if (top -> next == NULL) {return true;} else {return false;}}void pushStack(node *top, Element e) {node *p = new node;if (p == NULL) {cout << "分配内存失败!请检查程序!" << endl;exit(-1);}p -> data = e;p -> next = top -> next;top -> next = p;}void popStack(node *top) {if (isEmpty(top)) {cout << "该栈为空!" << endl;return;}node *p = top -> next;top -> next = p -> next;delete p;}void clearStack(node *top) {if (isEmpty(top)) {cout << "该栈为空!" << endl;return;}node *p;while (top -> next){p = top -> next;delete top;top = p;}delete top;cout << "该栈已经被清空!" << endl;}Element topStack(node *top) {return top -> next -> data;}int main(){int n;node *stack1 = initStack();cout << "请输入您想要插入栈的数据的个数: [10] ";cin >> n;for (int i = 1; i <= n; ++i) {Element data;cout << "请输入您想插入栈中的数据: ";cin >> data;pushStack(stack1, data);}cout << "*************************************************************" << endl;cout << "您输入的数据是: " << endl;for (int i = 1; i <= n; ++i) {cout << "第 " << i << " 个数是 " << topStack(stack1) << endl;popStack(stack1);}clearStack(stack1);return 0;}
运行结果:



0 0
原创粉丝点击