C语言实现顺序栈
main.c
#include "stack.h"
void test();
ElementType dataArray[] = {
{1,"侠客行"},
{2,"将进酒"},
{3,"神来之笔"},
{4,"青莲剑歌"}
};
int main()
{
test();
return 0;
}
void test(){
SeqStack seqstack;
ElementType * element = (ElementType *)malloc(sizeof(SeqStack));
InitSeqStack(&seqstack);
for (int i=0;i<4;i++){
PushSeqStack(&seqstack,dataArray[i]);
printf("当前入栈:%d\t%s.\n",dataArray[i].id,dataArray[i].name);
}
PopSeqStack(&seqstack,element);
printf("当前出栈:%d\t%s.\n",element->id,element->name);
}
stack.h
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 255
#define TRUE 1
#define FALSE 0
typedef struct {
int id;
char * name;
}ElementType;
typedef struct SeqStack{
ElementType elements[MAX_SIZE];
int top;
int length;
}SeqStack;
void InitSeqStack(SeqStack * seqstack);
int PushSeqStack(SeqStack * seqstack,ElementType element);
int PopSeqStack(SeqStack * seqstack,ElementType * element);
void ClearSeqStack(SeqStack * seqstack);
void GetTopElement(SeqStack * seqstack,ElementType * element);
#endif
stack.c
#include "stack.h"
void InitSeqStack(SeqStack * seqstack){
seqstack->top = -1;
seqstack->length = 0;
}
int PushSeqStack(SeqStack * seqstack,ElementType element){
if(seqstack->top == MAX_SIZE-1){
printf("栈已满.");
return FALSE;
}
seqstack->top++;
seqstack->elements[seqstack->top] = element;
seqstack->length++;
return TRUE;
}
int PopSeqStack(SeqStack * seqstack,ElementType * element){
if (seqstack->top == -1){
printf("空栈,无法出栈.\n");
}
*element = seqstack->elements[seqstack->top];
seqstack->length--;
seqstack->top--;
return TRUE;
}
void ClearSeqStack(SeqStack * seqstack){
seqstack->length = 0;
seqstack->top = -1;
}
void GetTopElement(SeqStack * seqstack,ElementType * element){
if (seqstack->top == 1){
printf("空栈.");
element = NULL;
return;
}
*element = seqstack->elements[seqstack->top];
}
|