#define StackSize 100
typedef char DataType;
class stack
{
public:
DataType data[StackSize];
int top;
void Initial();
bool IsEmpty();
bool IsFull();
void Push(DataType x);
DataType Pop();
DataType Top();
};
stack.cpp
#include "stack.h"
#include <iostream>
using namespace std;
void stack::Initial()
{
top = -1;
}
bool stack::IsEmpty()
{
return top == -1;
}
bool stack::IsFull()
{
return top == StackSize -1;
}
void stack::Push(DataType x)
{
if(IsFull() == true )
{
cout<< "栈?已??满??" <<endl;
}
else
{
top++;
data[top] = x;
}
}
DataType stack::Pop()
{
if(IsEmpty() == true )
{
cout<< "栈?为a空?" <<endl;
}
else
{
DataType temp;
temp = data[top];
top--;
return temp;
}
}
DataType stack::Top()
{
if(IsEmpty() == true )
{
cout<< "栈?为a空?" <<endl;
}
else
{
DataType temp;
temp = data[top];
return temp;
}
}
LinkStack.h
typedef char DataType;
typedef struct node
{
DataType data;
struct node *next;
}StackNode;
class LinkStack
{
public:
StackNode *top;
void Initial();
bool IsEmpty();
void Push(DataType x);
DataType Pop();
DataType Top();
};
LinkStack.cpp
#include "LinkStack.h"
#include <iostream>
using namespace std;
void LinkStack::Initial()
{
top = NULL;
}
bool LinkStack::IsEmpty()
{
return top == NULL;
}
void LinkStack::Push(DataType x)
{
StackNode *temp=(StackNode *)malloc( sizeof(StackNode)); //不?可??以??直??接??StackNode *temp;
temp->data = x;
temp->next = NULL;
//注???意?a栈?的??插?入?? 指?针?指?向??方??式??
temp->next = top;
top = temp;
}
DataType LinkStack::Pop()
{
DataType x;
StackNode *temp = top; //保???留??栈?顶??指?针?
if(IsEmpty())
{
cout<< "栈?为a空?" <<endl;
}
else
{
x = temp->data;
top = temp->next;
free(temp);
return x;
}
}
DataType LinkStack::Top()
{
DataType x;
StackNode *temp = top; //保???留??栈?顶??指?针?
if(IsEmpty())
{
cout<< "栈?为a空?" <<endl;
}
else
{
x = temp->data;
return x;
}
}
main.cpp
#include <stdio.h>
#include <iostream>
#include "stack.h"
#include "LinkStack.h"
using namespace std;
int main()
{
//printf("Hello
");
//stack mystack;
//mystack.Initial();
//mystack.Push('a');
//cout<<mystack.Top()<<endl;
//mystack.Push('b');
//cout<<mystack.Top()<<endl;
//cout<<mystack.Pop()<<endl;
//cout<<mystack.Pop()<<endl;
//mystack.Pop();
LinkStack mylinkstack;
mylinkstack.Initial();
mylinkstack.Push( 'x');
cout<<mylinkstack.Top()<<endl;
mylinkstack.Push( 'y');
cout<<mylinkstack.Top()<<endl;
cout<<mylinkstack.Pop()<<endl;
cout<<mylinkstack.Pop()<<endl;
mylinkstack.Pop();
return 0;
}