栈–链表实现
全部代码
#include <iostream>
#include <stdexcept>
using namespace std;
template<typename T>
//栈的链表实现
class Stack{
private:
struct Node{
T data;
Node *next;
Node(T d) : data(d),next(NULL){}
};
Node *head;//栈顶指针
int size;
public:
Stack():head(NULL),size(0) {}
~Stack();//析构函数(销毁栈)
void push(T element);//入栈函数
T pop();//出栈函数
T top() const;//获取栈顶元素
int getsize() const;//获取栈的长度
};
//析构函数(销毁栈)
template<typename T>
Stack<T>::~Stack(){
while(head){
Node*temp = head;
head = head->next;
delete temp;
}
}
//入栈函数
template<typename T>
void Stack<T>::push(T element){
Node *newnode = new Node(element);
newnode->next = head;
head = newnode;
++size;
}
//出栈函数
template<typename T>
T Stack<T>::pop(){
if(head == NULL){
throw std::underflow_error("Stack is empty");
}
T result = head->data;
Node *temp = head;
head = head->next;
delete temp;
--size;
return result;
}
//获取栈顶元素
template<typename T>
T Stack<T>::top() const{
if(head == NULL){
throw std::underflow_error("Stack is empty");
}
return head->data;
}
//获取栈的长度
template<typename T>
int Stack<T>::getsize() const{
return size;
}
int main(){
Stack<int> st;
st.push(4);
st.push(7);
st.push(13);
cout<<st.top()<<endl;
st.push(17);
cout<<st.top()<<endl;
st.pop();
st.pop();
cout<<st.top()<<endl;
cout<<st.getsize() << endl;
return 0;
}
结构体
class Stack{
private:
struct Node{
T data;
Node *next;
Node(T d) : data(d),next(NULL){}
};
Node *head;//栈顶指针
int size;
public:
Stack():head(NULL),size(0) {}
~Stack();//析构函数(销毁栈)
void push(T element);//入栈函数
T pop();//出栈函数
T top() const;//获取栈顶元素
int getsize() const;//获取栈的长度
};
析构函数
template<typename T>
Stack<T>::~Stack(){
while(head){
Node*temp = head;
head = head->next;
delete temp;
}
}
入栈函数
template<typename T>
void Stack<T>::push(T element){
Node *newnode = new Node(element);
newnode->next = head;
head = newnode;
++size;
}
出栈函数
template<typename T>
T Stack<T>::pop(){
if(head == NULL){
throw std::underflow_error("Stack is empty");
}
T result = head->data;
Node *temp = head;
head = head->next;
delete temp;
--size;
return result;
}
获取栈顶元素
template<typename T>
T Stack<T>::top() const{
if(head == NULL){
throw std::underflow_error("Stack is empty");
}
return head->data;
}
获取栈长度
template<typename T>
int Stack<T>::getsize() const{
return size;
}
测试
int main(){
Stack<int> st;
st.push(4);
st.push(7);
st.push(13);
cout<<st.top()<<endl;
st.push(17);
cout<<st.top()<<endl;
st.pop();
st.pop();
cout<<st.top()<<endl;
cout<<st.getsize() << endl;
return 0;
}