首页 > 编程语言 >数据结构代码整理_栈Stack(C++)

数据结构代码整理_栈Stack(C++)

时间:2023-06-20 10:00:44浏览次数:43  
标签:node Node top C++ new entry 数据结构 Stack


       所谓栈,就是先进后出规则的实现,这种数据结构在DFS等算法体现的较为明显,因为课程要求不得不进行各种数据结构实现代码整理,就发出来与大家分享。下面有两种实现方法一个是基于数组实现的,另一个是基于链表实现的。

基于数组实现

源码

main.cpp
//main.cpp : 定义控制台应用程序的入口点。
#include <iostream>
using namespace std;
#include "UTILITY.h"
#include "stack.h"
//typedef double Stack_entry;
int main()
{
    int n;
    float item;
    Stack numbers;
    cout << " Type in an integer n followed by n floating point numbers.\n"
        << " The numbers will be printed in reverse order." << endl;
    cin >> n;//输入字符数目
    for (int i = 0; i < n; i++) {
        cin >> item;
        if (numbers.push(item) == overflow)
            cout << "\nThe stack is full." << endl;
    }
    cout << "\n\n";
    while (!numbers.empty()) {
        numbers.top(item);
        numbers.pop();
        cout << item << " ";
    }
    cout << endl;
    return 0;
}
STACK.h
const int maxstack = 10; // small value for testing
typedef float Stack_entry; // The program will use stacks with float entries. 
enum Error_code {
    success, fail, range_error, underflow, overflow, fatal,
    not_present, duplicate_error, entry_inserted, entry_found,
    internal_error
};
class Stack {
public:
    Stack();
    bool empty() const;
    Error_code pop();
    Error_code top(Stack_entry& item) const;
    Error_code push(const Stack_entry& item);
private:
    int count;
    Stack_entry entry[maxstack];
};

Stack::Stack()
/*
Pre: None.
Post: The stack is initialized to be empty.
*/
{
    count = 0;
}
Error_code Stack::push(const Stack_entry& item)
/*
Pre: None.
Post: If the Stack is not full, item is added to the top
of the Stack. If the Stack is full,
an Error_code of overflow is returned and
the Stack is left unchanged.
*/
{
    Error_code outcome = success;
    if (count >= maxstack)
        outcome = overflow;
    else
        entry[count++] = item;
    return outcome;
}
Error_code Stack::top(Stack_entry& item) const
/*
Pre: None.
Post: If the Stack is not empty, the top of
the Stack is returned in item. If the Stack
is empty an Error_code of underflow is returned.
*/
{
    Error_code outcome = success;
    if (count == 0)
        outcome = underflow;
    else
        item = entry[count - 1];
    return outcome;
}
bool Stack::empty() const
/*
Pre: None.
Post:
If the Stack is empty, true is returned.
Otherwise false is returned.
*/
{
    bool outcome = true;
    if (count > 0) outcome = false;
    return outcome;
}
Error_code Stack::pop()
/*
Pre: None.
Post: If the Stack is not empty, the top of
the Stack is removed. If the Stack
is empty, an Error_code of underflow is returned.
*/
{
    Error_code outcome = success;
    if (count == 0)
        outcome = underflow;
    else --count;
    return outcome;
}

基于链表实现

源码

main.cpp

#include<iostream>
#include"Stack.h"
using namespace std;

int main()
{
	Stack s;
	s.push('a');
	s.push('b');
	char c;
	s.top(c);
	cout << c;
	return 0;
}

Stack.h

#pragma once
#include"Node.h"
#pragma once
enum Error_code {
    success, fail, range_error, underflow,
    overflow, fatal, not_present, duplicate_error,
    entry_inserted, entry_found, internal_error
};

class Stack {
public:
    //  Standard Stack methods
    Stack() { top_node = nullptr; };
    bool empty() const;
    Error_code push(const Stack_entry& item);
    Error_code pop();
    Error_code top(Stack_entry& item) const;
    //  Safety features for linked structures
    ~Stack();
    Stack(const Stack& original);
    void operator =(const Stack& original);
protected:
    Node* top_node;
};


Error_code Stack::push(const Stack_entry& item)
/* Post: Stack_entry item is added to the top of the Stack; returnssuccess or returns
a code of overflow if dynamic memory is exhausted. */ {
    Node* new_top = new Node(item, top_node);//倒着来
    if (new_top == NULL)
        return overflow;
    new_top->next=top_node;
    top_node = new_top;
    return success;
}
Error_code Stack::pop()
/* Post: The top of the Stack is removed. If the Stack is empty the method returns
underflow; otherwise it returns success. */ {
    Node* old_top = top_node;
    if (top_node == NULL)//空栈
        return underflow;
    top_node = old_top->next;
    delete old_top;//防止内存泄漏
    return success;
}
void Stack::operator = (const Stack& original) //深拷贝  Overload assignment
/*
Post: The Stack is reset as a copy of Stack original.
*/
{
    while (!empty())               //  Clean out old Stack entries
    pop();
    Node* new_top, * new_copy, * original_node = original.top_node;
    if (original_node == NULL)
        new_top = NULL;
    else {                         //  Duplicate the linked nodes
        new_copy = new_top = new Node(original_node->entry);
        while (original_node->next != NULL) {//正插(因为只能从栈顶开始,负负为正)
            original_node = original_node->next;
            new_copy->next = new Node(original_node->entry);
            new_copy = new_copy->next;
        }
    }
    top_node = new_top;            //  and replace them with new entries.
}
Stack::~Stack() //  Destructor
/*
Post: The Stack is cleared.
*/
{
    while (!empty())
        pop();
}
bool Stack::empty() const
{
    return top_node == NULL;
}
Stack::Stack(const Stack& original) //深拷贝  copy constructor
/*
Post: The Stack is initialized as a copy of Stack original.
*/
{
    Node* new_copy, * original_node = original.top_node;
    if (original_node == NULL)
        top_node = NULL;
    else {                         //  Duplicate the linked nodes.
        top_node = new_copy = new Node(original_node->entry);
        while (original_node->next != NULL) {
            original_node = original_node->next;
            new_copy->next = new Node(original_node->entry);
            new_copy = new_copy->next;
        }
    }
}

Error_code Stack::top(Stack_entry& item) const {
    if (!top_node)
        return underflow;
    else
        item = top_node->entry;
    return success;
}

Node.h

#pragma once
#include <cstddef>
typedef char Stack_entry;
typedef Stack_entry Node_entry;
class Node {
public:
    Node_entry entry;
    Node* next;
    Node();
    Node(Node_entry item, Node* add_on = NULL);
};
Node::Node()
{
    next = NULL;
}
Node::Node(Node_entry item, Node* add_on)
{
    entry = item;
    next = add_on;
}


标签:node,Node,top,C++,new,entry,数据结构,Stack
From: https://blog.51cto.com/u_16165815/6520519

相关文章

  • C++使用ranges库解析INI文件
    C++使用ranges库解析INI文件引言C++20引入了<ranges>头文件,C++23对其进行了完善,本文将使用该头文件提供的adaptor编写一个简单的ini解析器。ini文件格式介绍一般的ini文件由section和entry部分,比如[section]key=value;Thisisentry.section和entry均独占一行,其中sectio......
  • C++四种类型转换
    篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++四种类型转换相关的知识,希望对你有一定的参考价值。const_cast主要用于删除变量的const属性,便于赋值constinta=2;int*p=const_cast<int*>(&a);*p=3;reinterpret_cast仅仅是重新解释类型,没有二进制的......
  • C++ 关键字四种cast类型转换
    1.23四种cast类型转换作用:克服c中强制类型转化带来的风险,C++引入四种更加安全的强制类型转换运算符(明确转换的目的,偏于程序的维护和分析)const_cast://1.去除const属性,将只读变为只读写//2.针对常量指针、常量引用和常量对象constchar*p;char*p1=const_cast<char*>(p......
  • C++ 数据类型转换详解之终极无惑
    程序开发环境:VS2017+Win32+Debug文章目录1.隐式数据类型转换2.显示数据类型转换3.C++新式类型转换3.1const_cast3.2static_cast3.3dynamic_cast3.3.1向下转换3.3.2交叉转换3.4reinterpret_cast4.重载相关类型转换操作符4.1不同类对象的相互转换4.2基本数据类型与类对象......
  • C++面试八股文:什么是智能指针?
    某日二师兄参加XXX科技公司的C++工程师开发岗位第19面:面试官:什么是智能指针?二师兄:智能指针是C++11引入的类模板,用于管理资源,行为类似于指针,但不需要手动申请、释放资源,所以称为智能指针。面试官:C++11引入了哪些智能指针?二师兄:三种,分别是shared_ptr、unique_ptr、和weak_ptr。......
  • C++面试八股文:什么是智能指针?
    某日二师兄参加XXX科技公司的C++工程师开发岗位第19面:面试官:什么是智能指针?二师兄:智能指针是C++11引入的类模板,用于管理资源,行为类似于指针,但不需要手动申请、释放资源,所以称为智能指针。面试官:C++11引入了哪些智能指针?二师兄:三种,分别是shared_ptr、unique_ptr、和weak_ptr。......
  • Go 设计模式|组合,一个对数据结构算法和职场都有提升的设计模式
    Go设计模式|组合,一个对数据结构算法和职场都有提升的设计模式原创 KevinYan11 网管叨bi叨 2023-01-1608:45 发表于北京收录于合集#用Go学设计模式24个大家好,我是每周在这里陪你进步的网管~,这次我们继续设计模式的学习之旅。本次要学习的是组合模式,这个模式呢,平时要做......
  • C++继承和派生
    #继承和派生在C++中,继承和派生是面向对象编程的两个重要概念,用于实现类与类之间的关系。继承是指一个类可以从另一个类中继承属性和方法,并且可以在此基础上扩展出自己的属性和方法。被继承的类称为基类(父类),继承的类称为派生类(子类)。在C++中,可以通过以下方式定义一个派生类:```c++cl......
  • c++ 2.0 总结
    class内存分配与释放#include<iostream>#include<memory>usingnamespacestd;classPerson{public:Person(){cout<<"personconstructor"<<endl;}~Person(){cout<<"person......
  • C++:STL库
    模板编程泛型编程STL常用组件lambda表达式异常处理内存处理部分数据结构部分算法STL由算法,容器,迭代器,适配器,仿函数(函数对象),空间适配器六大部件组成。我们将主要讲解容器,迭代器,算法和仿函数。适配器的部分会交给学员来实现,而空间适配器不会太过于深入。从上往下学习STL,学习曲......