h
#pragma once
#include "pch.h"
namespace stack {
class stacklist {
public:
void init(stacklist *);//普通栈
int push(stacklist *);//普通进栈
int pop(stacklist *);//普通出栈
void watch(stacklist * );//输出栈
void douinit(stacklist *);//双端栈
int doupush(stacklist *);
int doupop(stacklist *);
void linkinit(stacklist *);//链栈
int linkpush(stacklist * );
int linkpop(stacklist * );
private:
char data[max];
int top;
int doutop[2];
char linkdata;
class stacklist*next;
};
}
cpp
#include "pch.h"
#include "栈.h"
using namespace stack;
void stacklist::init(stacklist *s)
{
s->top = -1;
};
int stacklist::push(stacklist *s)
{
if (s->top == max - 1)
{
cout << "栈满了!" << endl;
return 0;
}
cout << "开始进栈" << endl;
char x = 0;
while (x != '\n'&&s->top<=max-1)
{
x = getchar();
s->top++;
s->data[s->top] = x;
}
watch(s);
return 1;
};
int stacklist::pop(stacklist *s)
{
if (s->top == 0)
{
cout << "是空栈!" << endl;
return 0;
}
loop: cout << "开始出栈,请填写数量" << endl;
int x = 0; cin >> x;
if(x>s->top)
{
cout << "太多了" << endl;
goto loop;
}
for (int i = 0; i <= x; i++)
{
s->top--;
}
watch(s);
return 1;
};
void stacklist::douinit(stacklist *s)
{
s->doutop[0] = -1;
s->doutop[1] = max;
}
int stacklist::doupush(stacklist *s)
{
char y;
if ((s->doutop[0]>0&&s->doutop[0]+s->doutop[1]==max-1)||(s->doutop[1] <max && s->doutop[0] + s->doutop[1] == max - 1))
{
cout << "栈满了!" << endl;
return 0;
}
cout <<"请选择双端栈"<<endl;
int x; cin >> x;
cout << "请输入" << endl; cin >> y;
switch (x)
{
case 0:
s->data[s->doutop[0] ]= y;
s->doutop[0]++;
case 1:
s->data[s->doutop[1]] = y;
s->doutop[1]++;
}
return 1;
};
int stacklist::doupop(stacklist *s)
{
if (s->doutop[0]==-1&& s->doutop[1]==max )
{
cout << "是空栈!" << endl;
return 0;
}
cout << "选择双端栈" << endl;
int x; cin >> x;
cout << "请输入" << endl;
switch (x)
{
case 0:
s->doutop[0]--;
case 1:
s->doutop[1]--;
}
return 1;
};
void stacklist::linkinit(stacklist *s)
{
s->top = -1;
s->next = NULL;
};
int stacklist::linkpush(stacklist *s)//其实就是链表头插法
{
stacklist *p=s; char x = '\0'; int y = 0;
cout << "请输入栈元素"<<endl;
while (x != '\n'&&s->top <= max - 1)
{
x = getchar();
p = new stacklist;
p->linkdata = x;
p->next = s->next;
s->next = p;
s->top++;
}
return 1;
};
int stacklist::linkpop(stacklist *s)
{
if (s== NULL)
{
cout << "空栈" << endl;
return 0;
}
while (s->next)
{
stacklist *r = s;
s = s->next;
watch(s);
delete r;
}
return 1;
};
void stacklist::watch(stacklist *s)
{
cout << "结果是" << endl;
if (sizeof(s) == 4)
{
while (s->next != NULL)
{
s = s->next;
cout << s->linkdata;
}
}
else {
for (int x = s->top; x >=0; x--)
{
cout << s->data[x] << endl;
}
}
}