数据结构-栈
来源:互联网 发布:北京用友软件代理商 编辑:程序博客网 时间:2024/06/15 00:18
栈:先进后出
这里以头插法创建链表形式作为栈的结构,最后插入的元素始终为链表头,而出栈时将删除链表头以实现先进后出,后进先出的特性
关于其应用值得一提的便是后缀表达式
/*********************************************** > Filename: Stack.cpp > Author: Pyt > Create: 2017-08-19 13:41:43************************************************/#include <iostream>using namespace std;template<typename T>class Stack{public: Stack(); ~Stack(); Stack(const Stack &t); Stack& operator=(const Stack &t); void push(const T &t); void pop(); bool empty() const; const T& top() const; void clear();private: struct Node{ Node *next; T val; Node(T x) : val(x), next(NULL){} }; Node *head; int cursize;};template<typename T>Stack<T>::Stack() : cursize(0), head(NULL){ }template<typename T>Stack<T>::~Stack(){ clear();}template<typename T>Stack<T>::Stack(const Stack &t) : cursize(t.cursize){ Node *pre = NULL; Node *obj = t.head; if(obj) { Node *tmp = new Node(obj->val); pre = head = tmp; obj = obj->next; } else{ head = NULL; } while(obj) { Node *tmp = new Node(obj->val); pre->next = tmp; pre = tmp; obj = obj->next; }}template<typename T>Stack<T>& Stack<T>::operator=(const Stack &t){ if(this != &t) { Stack<T> tmp(t); swap(head, tmp.head); cursize = tmp.cursize; } return *this;}template<typename T>void Stack<T>::push(const T& t){ if(head == NULL) { head = new Node(t); } else{ Node *tmp = head; head = new Node(t); head->next = tmp; } cursize++;}template<typename T>void Stack<T>::pop(){ if(!empty()) { Node *tmp = head; head = head->next; delete tmp; cursize--; }}template<typename T>bool Stack<T>::empty() const{ return cursize == 0;}template<typename T>const T& Stack<T>::top() const{ if(!empty()) return head->val;}template<typename T>void Stack<T>::clear(){ while(head) { Node *tmp = head; head = head->next; delete tmp; } head = NULL; cursize = 0;}int main(){ Stack<int> a; for(int i=0; i<10; i++) a.push(i); Stack<int> b(a); b.pop(); cout << b.top() << " " << a.top() << endl; while(!a.empty()) { cout << a.top() << endl; a.pop(); } Stack<int> c; c = b; c.clear(); cout << c.empty() << endl; return 0;}
阅读全文
0 0
- 数据结构---栈
- 数据结构-栈
- 数据结构 栈
- 数据结构--栈
- 数据结构 栈
- 数据结构(栈)
- 数据结构栈
- 数据结构-栈
- 数据结构-----栈
- 数据结构-栈
- 【数据结构】栈
- 数据结构---->栈
- 数据结构---栈
- 数据结构--栈
- 数据结构----栈
- 数据结构--栈
- 【数据结构】 栈
- 数据结构 -- 栈
- Django资源大全
- POJ1741 [Tree] 点分治
- Android应用组件之Activity介绍1
- 关于复制构造函数赋值函数
- Selenium
- 数据结构-栈
- 79. Word Search
- 静态链接库和动态链接库的区别及优缺点
- Arduino智能小车——拼装篇
- Servlet之forward、sendRedirect、 include区别与使用
- Struts中继承接口SessionAware来实现session中的map集合
- 慕课笔记--[课程]Less即学即问
- python基础语法
- Eclipse超级完美汉化教程