用C语言描述栈,以下是源代码:
#include "stack.h"
Stack CreatStack(void)
{
PtrToNode S = (PtrToNode)malloc(sizeof(Node));
if (S == NULL)
{
printf("Out of space!\r\n");
return NULL;
}
S->Next = NULL;
memset(&(S->Element), 0, sizeof(ElementType));
return S;
}
bool IsEmpty(Stack S)
{
return (S->Next == NULL);
}
bool MakeEmpty(Stack S)
{
while (!IsEmpty(S))
{
Pop(S);
}
return false;
}
bool Push(Stack S, ElementType X)
{
PtrToNode TmpCell;
TmpCell = (PtrToNode)malloc(sizeof(Node));
if (TmpCell == NULL)
{
printf("Out of space!\r\n");
return false;
}
TmpCell->Element = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
ElementType Top(Stack S)
{
ElementType ret;
memset(&ret, 0, sizeof(ElementType));
if (IsEmpty(S))
{
printf("Empty Stack!\r\n");
return ret;
}
return S->Next->Element;
}
bool Pop(Stack S)
{
PtrToNode TmpCell;
if (IsEmpty(S))
{
printf("Empty Stack!\r\n");
return false;
}
TmpCell = S->Next;
S->Next = S->Next->Next;
free(TmpCell);
return true;
}
bool PrintAllNode(Stack S)
{
PtrToNode temp;
temp = S;
if (IsEmpty(temp))
{
printf("Empty Stack!\r\n");
return false;
}
uint16_t ElementCnt = 0;
while (!IsEmpty(temp))
{
printf("No %d element is: %c %d\r\n", ++ElementCnt, temp->Next->Element.ch, temp->Next->Element.Index);
temp = temp->Next;
}
printf("******** End ********\r\n");
return true;
}
#ifndef __STACK_H_
#define __STACK_H_
#include <stdbool.h>
#include <stdint.h>
#include <malloc.h>
#include <stdbool.h>
#include <stdio.h>
#include <memory.h>
typedef struct
{
uint16_t Index;
char ch;
}ElementType;
typedef struct node
{
ElementType Element;
struct node *Next;
}Node;
typedef Node *PtrToNode;
typedef PtrToNode Stack;
Stack CreatStack(void);
bool IsEmpty(Stack S);
bool MakeEmpty(Stack S);
bool Push(Stack S, ElementType X);
ElementType Top(Stack S);
bool Pop(Stack S);
bool PrintAllNode(Stack S);
#endif