顺序栈的C实现

来源:互联网 发布:软件测试说明书 编辑:程序博客网 时间:2024/05/21 07:00

测试文件:

#include <stdio.h>#include "seq_stack.h"int main(){    int array[] = {3,2,1,4,5,6,7};    pstack ps = init_stack();    ps = create_stack(array, 7);    // int i;    // for(i=0; i<7; i++)    //     push(ps, array[i]);    display_stack(ps);    ps = push(ps, 8);    ps = push(ps, 9);    pop(ps);    display_stack(ps);    return 0;}

实现文件

#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include "seq_stack.h"#define TRUE        0#define FALSE       1#define MAX_SIZE    1024pstack init_stack(){    int i;    pstack ps;    if((ps = (pstack)malloc(sizeof(s_stack))) == NULL){        printf("Init sequence stack error\n");        return NULL;    }    ps->top = -1;    ps->array = (Element *)malloc(sizeof(Element));        return ps;}pstack create_stack(Element *arr, int len){    if(len > MAX_SIZE){        printf("Wrong array length");        return NULL;    }    int i;    pstack ps = init_stack();    for(i=0; i<len; i++)    {        ps->array[i] = arr[i];        ps->top++;    }    return ps;}int is_empty(pstack ps){    return ((ps->top == -1)?TRUE : FALSE);}int is_full(pstack ps){    return ((ps->top == MAX_SIZE)?TRUE : FALSE);}Element get_top(pstack ps){    if(is_empty(ps) == 0)    {        printf("Sequence stack is empty\n");        return 0;    }    else        return ps->array[ps->top];}Element pop(pstack ps){    if(is_empty(ps) == 0)        return 0;    ps->top--;    return ps->array[ps->top+1];   }pstack push(pstack ps, Element e){    if(is_full(ps) == 0)    {        printf("Sequence stack is full\n");        return ps;      }    ps->top++;    ps->array[ps->top] = e;        return ps;}void display_stack(pstack ps){    int t = ps->top;    if(is_empty(ps) == 0)        printf("Sequence stack is empty\n");    else    {        while(t != -1)        {            printf("%d ", ps->array[t]);            t--;        }        printf("\n");    }}

头文件:

#ifndef STACK_H_INCLUDED#define STACK_H_INCLUDEDtypedef int Element;// top points to the top node of the stacktypedef struct s_stack{    int top;    Element* array;}s_stack, *pstack;pstack init_stack();pstack create_stack(int *arr, int len);int is_empty(pstack ps);int is_full(pstack ps);Element get_top(pstack ps);Element pop(pstack ps);pstack push(pstack ps, Element e);void display_stack(pstack ps);typedef struct l_stack{    int top;}l_stack;#endif // STACK_H_INCLUDED



0 0
原创粉丝点击