头文件:
#ifndef STACK_H
#define STACK_H
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType; // 初始化SElemType类型,这里根据需要修改基本类型
typedef struct SElemType {
ElemType data;
struct SElemType *next;
}SElemType,*SNode;
typedef struct {
SElemType *top; // 栈顶指针
}SqStack;
// ------ 基本操作的函数原型说明 ------
// 构造一个空栈S
Status InitStack( SqStack *S );
// 销毁栈S,S不再存在
Status DestroyStack( SqStack *S );
// 把S置为空栈
Status ClearStack( SqStack *S );
// 若栈S为空栈,则返回TRUE,否则返回FALSE
Status StackEmpty( SqStack S );
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
Status GetTop( SqStack S, ElemType *e );
// 插入元素e为新的栈顶元素
Status Push( SqStack *S, ElemType e );
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop( SqStack *S, ElemType *e );
// 从栈底到栈顶依次对栈中的每个元素调用函数visit().一旦visit()失败,则操作失败
Status StackTraverse( SqStack S, Status (*visit)());
#endif
实现代码:
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
// ------ 基本操作的算法描述------
// 构造一个空栈S
Status InitStack( SqStack *S )
{
SElemType *head = (SElemType *)malloc(sizeof(SElemType));
if ( !head )
return ERROR;
head->next = NULL;
S->top = head;
return OK;
}// InitStack
// 销毁栈S,S不再存在
Status DestroyStack( SqStack *S )
{
SNode ptr,temp;
ptr = S->top;
while( !ptr )
{
temp = ptr;
ptr = temp->next;
free(temp);
}
return OK;
}
// 把S置为空栈
Status ClearStack( SqStack *S )
{
SNode ptr,temp;
if ( StackEmpty( *S ) )
return OK;
temp = S->top;
ptr = temp->next;
while( !ptr )
{
temp = ptr;
ptr = temp->next;
free(temp);
}
S->top->next = NULL;
return OK;
}
// 若栈S为空栈,则返回TRUE,否则返回FALSE
Status StackEmpty( SqStack S )
{
if ( S.top->next == NULL )
return TRUE;
return FALSE;
}
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
Status GetTop( SqStack S, ElemType *e )
{
if (StackEmpty(S))
return ERROR;
*e = S.top->next->data;
return OK;
}
// 插入元素e为新的栈顶元素
Status Push( SqStack *S, ElemType e )
{
SNode tempPtr = (SNode)malloc(sizeof(SElemType));
if ( !tempPtr )
return FALSE;
tempPtr->data = e;
tempPtr->next = S->top->next;
S->top->next = tempPtr;
return OK;
}
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop( SqStack *S, ElemType *e )
{
SNode temp;
if (StackEmpty(*S))
return ERROR;
temp = S->top->next;
*e = temp->data;
S->top->next = temp->next;
free(temp);
return OK;
}
// 从栈底到栈顶依次对栈中的每个元素调用函数visit().一旦visit()失败,则操作失败
Status StackTraverse( SqStack S, Status (*visit)())
{
SElemType *ptr = S.top;
while( !ptr )
{
if (!visit())
exit(0);
ptr=ptr->next;
}
return OK;
}
1,若栈的元素是基本数据类型,请打开stack.h
将第17行的typedef int ElemType;中的int改成相对应的数据类型。
2.若栈的元素不是基本数据类型,而是结构体类型,可执行下面两种操作:
(1).将该结构体定义放在stack.h中的SqStack结构体前面,并用typedef name ElemType; 重命名结构体
(2).用#include语句将含有结构体元素的头文件包含进来,并用typedef name ElemType; 重命名结构体
如
struct A{
int c;
};
typedef struct A ElemType;