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

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

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

    #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;
    }
    运行结果:



  • 相关阅读:
    java小知识点8
    MongoDB执行计划分析详解(1)
    面对Schema free 的MongoDB,如何规范你的schema
    Mongodb简介
    编程之法:面试和算法心得(最大连续乘积子串)
    编程之法:面试和算法心得(荷兰国旗)
    编程之法:面试和算法心得(奇偶调序)
    编程之法:面试和算法心得(最大连续子数组和)
    编程之法:面试和算法心得(寻找和为定值的多个数)
    744. Find Smallest Letter Greater Than Target
  • 原文地址:https://www.cnblogs.com/wiklvrain/p/8179483.html
Copyright © 2020-2023  润新知