顺序栈
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef char ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int top;
}Sqstack;
void InitStack(Sqstack *&stack)
{
stack = new Sqstack;
stack->top = -1;
}
void DestoryStack(Sqstack *&stack)
{
delete stack;
}
bool StackEmpty(Sqstack *stack)
{
return stack->top + 1;
}
bool Push(Sqstack *&stack, ElemType e)
{
if(stack->top == MAXSIZE - 1)
return false;
stack->data[++stack->top] = e;
return true;
}
bool Pop(Sqstack *&stack, ElemType &e)
{
if(stack->top == -1)
return false;
e = stack->data[stack->top--];
return true;
}
void GetTop(Sqstack *stack, ElemType &e)
{
e = stack->data[stack->top];
}
bool Symmetry(ElemType str[])
{
return true;
}
bool bracketsmatching(ElemType str[])
{
return true;
}
int main()
{
ElemType e;
Sqstack *stack;
InitStack(stack);
if(StackEmpty(stack))
printf("栈为空");
else
printf("栈为空");
Push(stack, 'a');
Push(stack, 'b');
Push(stack, 'c');
GetTop(stack, e);
cout << e << endl;
Pop(stack, e);
cout << e << endl;
Pop(stack, e);
cout << e << endl;
Pop(stack, e);
cout << e << endl;
return 0;
}
链栈
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef char ElemType;
typedef struct Node
{
ElemType date;
struct Node *next;
}Linkstack, Node;
void InitStack(Linkstack *&stack)
{
stack = new Linkstack;
}
void ClearStack(Linkstack*& stack)
{
Linkstack* p = stack;
Linkstack* temp;
while (p = p->next)
{
temp = p;
p = p->next;
delete temp;
}
}
void DestoryStack(Linkstack *&stack)
{
ClearStack(stack);
delete stack;
}
bool StackEmpty(Linkstack *stack)
{
return stack->next == NULL;
}
bool Push(Linkstack *&stack, ElemType e)
{
Node *temp = new Node;
temp->date = e;
temp->next = stack->next;
stack->next = temp;
return true;
}
bool Pop(Linkstack *&stack, ElemType &e)
{
Node *temp;
if(stack->next == NULL)
return false;
e = stack->next->date;
temp = stack->next;
stack->next = stack->next->next;
delete temp;
return true;
}
bool GetTop(Linkstack *stack, ElemType &e)
{
if(stack->next == NULL)
return false;
e = stack->next->date;
return true;
}
int main()
{
ElemType e;
Linkstack *stack;
InitStack(stack);
if(StackEmpty(stack))
cout << "栈为空" << endl;
else
cout << "栈不为空" << endl;
Push(stack, 'a');
Push(stack, 'b');
Push(stack, 'c');
GetTop(stack, e);
cout << "栈顶元素是:" << e << endl;
Pop(stack, e);
cout << e << endl;
Pop(stack, e);
cout << e << endl;
Pop(stack, e);
cout << e << endl;
DestoryStack(stack);
return 0;
}