栈是一种特殊的链表,具有“先进后出”、“后进先出”的特点,它的插入和删除操作只能在栈的顶部进行。生活中的很多场景具有这种特点,例如火车的调度,碗的叠垒等。利用栈可完美解决这一类问题。
本文简单实现了栈的初始化、插入、删除、输出操作,代码如下。
#include<iostream>
#include<numeric>
#include<stack>
using namespace std;
struct stacks
{
int data;
stacks *next;
};
struct node
{
int size;
stacks *top;
stacks *base;
};
node s;
void init()
{
stacks *k=(stacks*)new stacks, *news;
s.base = (stacks*)new stacks;
s.top = s.base;
int x,n;
cout << "输入栈的长度:";
cin >> n;
s.size = n;
for (int i = 1; i <= n; i++)
{
news = (stacks*)new stacks;
cout << "输入第" << i << "个元素:";
cin >> x;
news->data = x;
news->next = NULL;
if (i == 1)
{
k = news;
s.base = k;
s.top = (stacks*)new stacks;
s.top->next = k;
}
else
{
news->next = k;
k = news;
s.top->next=news;
}
}
}
void output()
{
node q;
q = s;
cout << "输出栈:";
do
{
cout << q.top->next->data << " ";
q.top=q.top->next;
} while (q.base != q.top);
cout << endl;
}
void push()
{
stacks *push = (stacks*)new stacks;
int x;
cout << "输入插入的元素:";
cin >> x;
push->data = x;
push->next =s.top->next;
s.top->next = push;
}
void pop()
{
cout << "依次删除栈顶元素并输出"<<endl<<"直至栈为空:";
stacks *pop;
pop = s.top;
do
{
cout << pop->next->data << " ";
pop = pop->next;
} while (pop != s.base);
}
int main()
{
init();
output();
push();
output();
pop();
return 0;
}