链表实现栈?
// 链表实现栈
#include<iostream>
using namespace std;
// 链表节点
class Node
{
public:
int data;
Node* next;
Node(){}
Node(int data):data(data),next(nullptr){}
};
// 链表栈
class ListStack
{
public:
Node* top;
int count;
public:
ListStack();
void push_stack(int data);
void pop_stack();
void show_stack();
};
ListStack::ListStack(){
this->top = NULL;
this->count = 0;
}
void ListStack::push_stack(int data){
Node* new_node = new Node(data);
new_node->next = this->top;
this->top = new_node;
this->count ++;
}
void ListStack::pop_stack(){
if(this->count){
Node* tmp = this->top;
this->top = top->next;
delete tmp;
tmp = NULL;
this->count --;
}
}
void ListStack::show_stack(){
if(this->top == NULL){
cout<<"the stack is empty!"<<endl;
}
else{
Node* cur = this->top;
while(cur != NULL){
cout<<cur->data<<',';
cur = cur->next;
}
delete cur;
cur = NULL;
cout<<endl;
}
}
int main()
{
ListStack* mystack = new ListStack();
mystack->show_stack();
mystack->push_stack(1);
cout<<"top= "<<mystack->top->data<<",count= "<<mystack->count<<endl;
mystack->show_stack();
mystack->push_stack(2);
cout<<"top= "<<mystack->top->data<<",count= "<<mystack->count<<endl;
mystack->show_stack();
mystack->pop_stack();
mystack->show_stack();
return 0;
}
链表实现队列
// 链表实现队列
#include<iostream>
using namespace std;
//链表节点
class Node
{
public:
int data;
Node* next;
public:
Node(){}
Node(int data):data(data),next(nullptr){}
};
//链表队列:头部删除,尾部添加(先去先出)
class ListQueue
{
public:
Node* front;
Node* rear;
int count;
public:
ListQueue(){
this->count = 0;
this->front = NULL;
this->rear = NULL;
}
void push_queue(int data);
void pop_queue();
void show_queue();
};
// 尾插 入队
void ListQueue::push_queue(int data){
Node* new_node = new Node(data);
if(this->rear != NULL){
this->rear->next = new_node;
this->rear = new_node;
}
else{
this->rear = new_node;
this->front = new_node;
}
this->count ++;
}
// 头部删除:出队
void ListQueue::pop_queue(){
//队列为空
if(this->front == NULL){
return;
}
else{
Node* tmp = this->front;
//队列只有一个元素
if(this->front == this->rear){
this->front = NULL;
this->rear = NULL;
}
else{
this->front = this->front->next;
}
delete tmp;
tmp = NULL;
this->count --;
}
}
//遍历队列
void ListQueue::show_queue(){
if(this->front == NULL){
cout << "the queue is empty" << endl;
}
else{
Node* cur = this->front;
while(cur != NULL){
cout<<cur->data<<", ";
cur = cur->next;
}
cout<<endl;
cout<<"count:"<<this->count<<endl;
}
}
int main()
{
ListQueue* myqueue = new ListQueue();
myqueue->show_queue();
myqueue->push_queue(1);
myqueue->push_queue(2);
myqueue->push_queue(3);
cout<<"front:"<<myqueue->front->data<<", rear:"<<myqueue->rear->data<<endl;
myqueue->show_queue();
myqueue->pop_queue();
myqueue->show_queue();
return 0;
}