1. 程式人生 > >一個簡單C順序棧的實現

一個簡單C順序棧的實現

僅用於記錄,加深理解的練習。
水平有限,不規範之處還請包涵指正。
只實現了初始化棧,進棧,出棧,列印資料功能。

#include<stdio.h>
#include<stdlib.h>

#define ADDSIZE 10
#define STARTSIZE 10

typedef int ElemType;
typedef struct
{
    ElemType *top;
    ElemType *base;
    int stacksize;
}Stack;                                 //define structure of stack
Stack *InitStack(Stack *); //initialize the stack int EmptyStack(Stack *); //judge if it is a empty or not int Push(Stack *,ElemType e); //send e in top of stack ElemType pop(Stack *); //pop data of top-1 void display(Stack *); //display the whole data of it
int main() { ElemType data; int choice; Stack *stack; stack=InitStack(stack); printf("--One empty stack has builded,choose a operation:"); while(1) { printf("\n--1.push stack\n--2.pop stack\n--3.display\n--"); scanf("%d",&choice); if(choice!=
1&&choice!=2&&choice!=3) { printf("\n--invaid choice,try again.\n--"); scanf("%d",&choice); } if(choice==1) { printf("--please input data to push in the top.\n--"); scanf("%d",&data); Push(stack,data); } if(choice==2) { if(EmptyStack(stack)) printf("\n--That stack is empty.No data can pop.\n--try again\n--"); else printf("\n--Operation over,%d leave stack.\n--",pop(stack)); } if(choice==3) display(stack); } } Stack *InitStack(Stack *s) { s=(Stack *)malloc(sizeof(Stack)); s->base=(ElemType *)malloc((sizeof(ElemType)*STARTSIZE)); s->top=s->base; s->stacksize=STARTSIZE; return s; } EmptyStack(Stack *s) //1 indicate the stack is empty { if(s->top==s->base) return 1; else return 0; } //because the data is continuous,judge if full or not by difference between top and base //if this stack is full,use realloc to get more memory,but s->base may be changed, //so. we should change s->top to adapt to the change int Push(Stack *s,ElemType e) { if((s->top)-(s->base)>=s->stacksize) { s->base=(ElemType *)realloc(s->base,(s->stacksize+ADDSIZE)*sizeof(ElemType)); s->top=s->base+s->stacksize; } *s->top=e; s->top++; return 1; } ElemType pop(Stack *s) { ElemType tep; tep=*(s->top-1); s->top--; return tep; } //use a temporary variable to display all value of stack void display(Stack *s) { ElemType *tem=s->base; printf("\n-------base of stack-------"); while(tem<s->top) printf("\n-------%13d-------",*tem++); printf("\n-------top of stack -------"); }

棧結構只包含兩個指標和一個記錄資料多少的整型變數,所以資料儲存的位置是另行開闢的,realloc函式有重新分配更多空間的能力,用於棧的擴充。