• 数据结构


    链栈封装 C++

    使用C++对链栈进行了简单的封装,实现了栈的基本操作
    封装方法: pop(),top(),size(),empty(),push()

    代码已经过测试

    #pragma once
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    template<class T>class LinkNode{
    public:	
    	T data;
    	LinkNode *pnext;
    	LinkNode *ppre;
    };
    template<class T>class Stack {
    public:
          	 Stack();       //构造函数
    	void pop();         //弹出头元素
    	void push(T value); //入栈
    	bool empty();       //判断是否为空栈
    	int  size();        //返回栈的大小
    	  T  top();         //获取首元素
    private:
    	LinkNode<T> *head;
    	LinkNode<T> *tail;
    	int len;
    };
    
    template<class T>
    inline Stack<T>::Stack()
    {
    	this->head = nullptr;
    	this->tail = nullptr;
    	this->len = 0;
    }
    
    template<class T>
    inline void Stack<T>::pop()
    {
    	if (this->head == this->tail)
    	{
    		this->head = this->tail = nullptr;
    		this->len  = 0;
    		return;
    	}
    	LinkNode<T> *p = this->tail;
    	this->tail = p->ppre;
    	this->tail->pnext = nullptr;
    	free(p);
    	p = nullptr;
    	this->len--;
    }
    
    template<class T>
    inline void Stack<T>::push(T value)
    {
    	LinkNode<T> *newnode = new LinkNode<T>;
    	newnode->data = value;
    	if (this->len == 0)
    	{
    		this->head = newnode;
    		this->tail = newnode;
    		this->len++;
    	}
    	else {
    		tail->pnext = newnode;
    		newnode->ppre = tail;
    		this->tail = newnode;
    		this->len++;
    	}
    }
    
    template<class T>
    inline bool Stack<T>::empty()
    {
    	if (this->len == 0)
    	return true;
    	else return false;
    }
    
    template<class T>
    inline int Stack<T>::size()
    {
    	return this->len;
    }
    
    template<class T>
    inline T Stack<T>::top()
    {
    	return T(this->tail->data);
    }
    

    如果大家有什么疑问的话可以加qq向我提出哦,欢迎各位大佬指出问题。
    如果你觉得对你有所帮助的话就给我点个赞,点燃我下次写文章的动力吧 ^_^ !

  • 相关阅读:
    jar
    8月21日23:38
    WPF之UI虚拟化
    (转)Windows系统白名单以及UAC机制
    C#获取文件版本信息
    命名实体识别,使用pyltp提取文本中的地址
    (转载)完成端口(Completion Port, I/OCP)详解
    全国各城市地名抓取,包含街道、村落、小区、商店、景点等
    关于Python打包运行的一些思路
    关于批判性思维(Critical Thinking)
  • 原文地址:https://www.cnblogs.com/wlw-x/p/11609681.html
Copyright © 2020-2023  润新知