#include<iostream>
using namespace std;
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef PtrToNode Position;
struct Node
{
int element;
PtrToNode next;
};
int IsEmpty(Stack S)
{
return S->next == NULL;
}
int Pop(Stack S)
{
int X;
PtrToNode FirstCell;
if (IsEmpty(S)) return -1;
else
{
FirstCell = S->next;
S->next = S->next->next;
X = FirstCell->element;
free(FirstCell);
cout << "弹出" << X << endl;
return 0;
}
cout << endl;
}
int MakeEmpty(Stack S)
{
if (S == NULL) return -1;
else
while (!IsEmpty(S))
Pop(S);
return 0;
}
Stack CreateStack()
{
Stack S = (PtrToNode)malloc(sizeof(struct Node));
S->next = NULL;
return S;
}
int Push(int X, Stack S)
{
PtrToNode TmpCell;
TmpCell = (PtrToNode)malloc(sizeof(struct Node));
if (TmpCell == NULL) return -1;
else {
TmpCell->element = X;
TmpCell->next = S->next;
S->next = TmpCell;
return 0;
}
}
int Top(Stack S)
{
int x;
if (!IsEmpty(S)) {
x = S->next->element;
return x;
}
return -1;
}
void Show(Stack& S)
{
Position p = S->next;
if (p == NULL)
cout << "栈已空!" << endl;
else
{
while (p != NULL)
{
cout << p->element << " ";
p = p->next;
}
}
cout << endl;
}
int main()
{
cout << "-----------创建栈测试------------" << endl;
Stack S;
S = CreateStack();
for (int i = 0; i < 10; i++)
{
Push(i, S);
}
Show(S);
cout << "-----------栈顶测试------------" << endl;
cout << "栈顶:" << Top(S) << endl;
cout << "-----------弹出栈测试------------" << endl;
Pop(S);
MakeEmpty(S);
cout << "栈置空后:";
Show(S);
cout << "-----------输入栈测试------------" << endl;
cout << "输入10后的栈:";
Push(10, S);
Show(S);
cout << "-----------输入栈后栈顶测试------------" << endl;
cout << "栈顶:";
cout<<Top(S);
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-41331.html