赞
踩
栈是限定仅在栈顶进行插入和删除操作的线性表,在操作的时候,只允许栈顶改变不允许栈底改变,具有后进先出的特征。
顺序栈是一种使用数组实现的栈,也称为数组栈。其基本思路是通过数组来存储栈中的元素,并通过栈顶指针指示栈顶元素在数组中的位置。
也就是说,相当于只能对最后一个元素进行增,删,查的数组。
- #ifndef SEQSTACK_H
- #define SEQSTACK_H
-
- typedef struct{
- char name[32];
- char sex;
- int age;
- int score;
- }DATATYPE;
-
- typedef struct
- {
- DATATYPE* head;
- int tlen;
- int top;// clen
- }SeqStack;
-
- SeqStack*CreateSeqStack(int size); //创建
- int DestroySeqStack(SeqStack*ss); //销毁
- int PushSeqStack(SeqStack*ss,DATATYPE*data); //入栈
- int PopSeqStack(SeqStack*ss); //出栈
- int IsEmptySeqStack(SeqStack*ss); //判断栈是否为空
- int IsFullSeqStack(SeqStack*ss); //判断栈是否为满
- int GetSizeSeqStack(SeqStack*ss); //获取栈当前大小
- DATATYPE*GetTopSeqStack(SeqStack*ss); //获取栈顶元素
- #endif // SEQSTACK_H

实现:
- #include "seqstack.h"
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- SeqStack *CreateSeqStack(int size)
- {
- SeqStack* ss = ( SeqStack*)malloc(sizeof(SeqStack));
- if(NULL ==ss)
- {
- perror("CreateSeqStack error malloc1");
- return NULL;
- }
- ss->head = ( DATATYPE*)malloc(sizeof(DATATYPE)*size);
- if(NULL ==ss->head)
- {
- perror("CreateSeqStack error malloc2");
- return NULL;
- }
- ss->tlen = size;
- ss->top = 0;
- return ss;
- }
-
- int PushSeqStack(SeqStack *ss, DATATYPE *data)
- {
- if(NULL == ss ||NULL ==data)
- {
- fprintf(stderr,"SeqStack or data is null \n");
- return 1;
- }
- if(IsFullSeqStack(ss))
- {
- fprintf(stderr,"PushSeqStack full\n");
- return 1;
- }
-
- memcpy(&ss->head[ss->top],data,sizeof(DATATYPE));
- ss->top++;
- return 0;
- }
-
- int PopSeqStack(SeqStack *ss)
- {
- if(NULL == ss )
- {
- fprintf(stderr,"SeqStack is null \n");
- return 1;
- }
- if(IsEmptySeqStack(ss))
- {
- fprintf(stderr,"PopSeqStack is empty \n");
- return 1;
- }
- ss->top--;
- return 0;
- }
-
- int IsEmptySeqStack(SeqStack *ss)
- {
- return 0 == ss->top;
- }
-
- int IsFullSeqStack(SeqStack *ss)
- {
- return ss->top == ss->tlen;
- }
-
- DATATYPE *GetTopSeqStack(SeqStack *ss)
- {
- if(IsEmptySeqStack(ss))
- {
- return NULL;
- }
- return &ss->head[ss->top-1];
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。