链表模拟栈:
#include <iostream>
#include "stdio.h"
#include "stack.cpp"
typedef int datatype;
using namespace std;
int main()
{
stack a;
a.push(3);
a.push(5);
cout<<a.top()<<endl;
cout<<a.isempty()<<endl;
a.pop();
cout<<a.top();
a.clear();
}
#include "stack.h"
stack::stack()
{
length=0;
node=NULL;
headnode=NULL;
}
int stack::getlength()
{
return length;
}
void stack::push(int x)
{
node=new stacknode;
node->data=x;
node->next=headnode;
headnode=node;
length++;
}
bool stack::isempty()
{
return length==0;
}
void stack::pop()
{
if (isempty())
return;
else
{
node=headnode;
headnode=node->next;
delete node;
length--;
}
}
int stack::top()
{
return headnode->data;
}
void stack::clear()
{
while(headnode!=NULL)
{
node=headnode;
headnode=headnode->next;
delete node;
}
node=NULL;
headnode=NULL;
length=0;
}
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
class stacknode
{
public:
stacknode()
{
next=NULL;
};
int data;
stacknode*next;
};
class stack
{
private:
int length;
stacknode*node;
stacknode*headnode;
public:
stack();
int getlength();
void push(int x);
bool isempty();
void pop();
int top();
void clear();
};
#endif // STACK_H_INCLUDED
数组模拟栈:
#include <iostream>
#include "stack.cpp"
using namespace std;
int main()
{
stack s;
int temp;
s.push(13);
s.push(114);
s.push(12);
s.push(1);
cout<<s.peek()<<endl;
if (!s.stackempty())
{
temp=s.pop();
}
cout<<temp<<endl;
s.clearstack();
}
#include "stack.h"
#include <stdlib.h>
using namespace std;
stack::stack()
{
top=-1;
}
void stack::push(const int &item)
{
if (top==maxstacksize)
{
cout<<"stackoverflow"<<endl;
exit(1);
}
top++;
stacklist[top]=item;
}
int stack::pop()
{
if (top==-1)
{
cout<<"stackempty"<<endl;
exit(1);
}
int temp;
temp=stacklist[top];
top--;
return temp;
}
void stack::clearstack()
{
top=-1;
}
int stack::peek()const
{
if (top==-1)
{
cout<<"stackempty"<<endl;
exit(1);
}
int temp;
temp=stacklist[top];
return temp;
}
int stack::stackempty()const
{
return top==-1;
}
int stack::stackfull()const
{
return top==maxstacksize-1;
}
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
#define maxstacksize 100
class stack
{
private:
int stacklist[maxstacksize];
int top;
public:
stack();
void push(const int &item);
int pop();
void clearstack();
int peek()const; //访问栈顶元素,等同于pop,但不将top-1,保持栈的状态不变
int stackempty()const; //检测是否栈空
int stackfull()const; //检测是否栈满
};
#endif // STACK_H_INCLUDED
转载于:https://www.cnblogs.com/liuziqi/p/5852524.html