链式栈:(代码)
#include <bits/stdc++.h>
using namespace std;
//栈元素
struct Stack
{
int data;
struct Stack *next;
};
Stack *top = NULL;//栈顶指针
//入栈
void push(int x)
{
Stack *p = new Stack;
p->data = x;
p->next = top;
top = p;//修改栈顶位置
}
//出栈
void pop()
{
Stack *p = top;
if(p != NULL)
{
cout<<p->data<<"出栈"<<endl;
p = p->next;
delete top;
top = p;//修改指针位置
}
else
{
cout<<"栈空"<<endl;
}
}
//获得栈长度
int getlen()
{
int len = 0;
Stack *p = top;
while(p != NULL)
{
len++;
p = p->next;
}
return len;
}
//显示栈元素
void display()
{
Stack *p = top;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main()
{
int order,x;
cout<<"输入指令:"<<endl;
while(1 == 1)
{
cout<<"1:入栈,2:出栈,3:显示,4:求栈长!"<<endl;
cin>>order;
if(order == 1)
{
cin>>x;
push(x);
display();
}
else if(order == 2)
{
pop();
display();
}
else if(order == 3)
{
display();
}
else if(order == 4)
{
cout<<getlen()<<endl;
}
}
return 0;
}
链式队列:(代码)
#include <bits/stdc++.h>
using namespace std;
//队列节点
struct Queue
{
int data;
struct Queue *next;
};
Queue *front = NULL;//队头
Queue *rear = NULL;//队尾
//入队
void add(int value)
{
Queue *e = new Queue;
e->data = value;
e->next = NULL;
//队列第一个元素
if(front == NULL)
{
front = e;
}
else
{
rear->next = e;
}
rear = e;
}
//出队
void del()
{
Queue *t;
//如果对列有元素
if(front != NULL)
{
cout<<front->data<<"出队"<<endl;
t = front;
front = front->next;
if(front == NULL) rear = NULL;
delete t;
}
else
{
cout<<"队列空"<<endl;
}
}
//显示队
void display()
{
Queue *p = front;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main()
{
int order,x;
cout<<"输入指令:"<<endl;
while(1 == 1)
{
cout<<"1:入队,2:出队,3:显示队!"<<endl;
cin>>order;
if(order == 1)
{
cin>>x;
add(x);
display();
}
else if(order == 2)
{
del();
display();
}
else if(order == 3)
{
display();
}
}
return 0;
}
标签:知识点,top,初赛,else,Queue,链式,Stack,NULL,order
From: https://blog.csdn.net/weixin_60445850/article/details/141883994