链表实现Stack
stack.h
#pragma once
#include <iostream>
#include <stdbool.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;
bool IsEmpty(Stack S);
Stack CreateStack();
void DisposeStack(Stack S); // 删除栈(把top指针也删除)
void MakeEmpty(Stack S); // 清空栈
void Push(ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
stack.cpp
#include "Stack.h"
#include <stdlib.h>
struct Node
{
ElementType Element;
PtrToNode Next;
};
bool IsEmpty(Stack S)
{
return S->Next == NULL;
}
Stack CreateStack()
{
Stack S = (Stack)malloc(sizeof(struct Node));
if (S == NULL)
std::cout<<"Out of space!"<<std::endl;
S->Next = NULL;
return S;
}
void DisposeStack(Stack S)
{
MakeEmpty(S);
free(S);
}
void MakeEmpty(Stack S)
{
if (S == NULL)
std::cout << "Must use CreateStack first!" << std::endl;
else
while (!IsEmpty(S))
Pop(S);
}
void Push(ElementType X, Stack S)
{
PtrToNode TmpCell = (PtrToNode)malloc(sizeof(struct Node));
if (TmpCell == NULL)
std::cout<<"Out of space!"<<std::endl;
TmpCell->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
ElementType Top(Stack S)
{
if (IsEmpty(S))
std::cout << "Empty Stack!" << std::endl;
return S->Next->Element;
}
void Pop(Stack S)
{
if (!IsEmpty(S))
{
PtrToNode TmpCell = S->Next;
S->Next = TmpCell->Next;
free(TmpCell);
}
else
std::cout << "Empty stack!" << std::endl;
}
ElementType TopAndPop(Stack S)
{
if (!IsEmpty(S))
{
PtrToNode TmpCell = S->Next;
ElementType Element = TmpCell->Element;
S->Next = TmpCell->Next;
free(TmpCell);
return Element;
}
else
std::cout<<"Empty stack!"<<std::endl;
}
main.c
#include <stdio.h>
#include "stack.h"
using namespace std;
int main()
{
Stack S;
S = CreateStack();
for (int i = 0; i < 10; i++)
Push(i, S);
TopAndPop(S); //抛出顶部的9
while (!IsEmpty(S))
{
printf("%d\n", Top(S));
Pop(S);
}
DisposeStack(S);
return 0;
}