ArrStack——数组栈(procedure)

//数组栈,对于无法预料栈的长度情况下,可能会因为原分配数组不够长而导致数据溢出,或因为数组太长而浪费空间。但是操作快,不需要额外的操作。而链表与此想法,可以动态分配内存,但是要增加额外的操作。
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

int main()
{
 int i;
 Type x;
 STACK *s = NULL;
 Type arr[] = {3,1,2,5,7,9};

s = CreateStack(10);
 if(s == NULL)
  return -1;

for(i = 0; i < sizeof(arr)/sizeof(*arr); i++)
 {
  PushStack(s, arr + i);
 }
 TopAndPopStack(s, &x);
 printf("x = %d\n", x);
 PosStack(s);
 TopOfStack(s, &x);
 printf("x = %d\n", x);
 
 return 0;
}
--------------------------------------------------------------------------

#ifndef _STACK_H__
#define _STACK_H__

struct node;
typedef int Type;
typedef struct node STACK;

STACK *CreateStack(int);
void StackMakeEmpty(STACK *);
int StackIsEmpty(STACK *);
int StackIsFull(STACK *);
int PushStack(STACK *, const Type *);
int PosStack(STACK *);
int TopOfStack(STACK *, Type *);
int TopAndPopStack(STACK *, Type *);
int DisposeStack(STACK *);

struct node{
 Type *data;
 int capacity;
 int topofstack;
};

#endif
-----------------------------------------------------------------------------

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

STACK *CreateStack(int size)
{
 STACK *s = malloc(sizeof(*s));
 if(NULL == s)
  return NULL;
 s->data = malloc(sizeof(Type)*size);
 if(NULL == s->data)
 {
  free(s);
  return NULL;
 }
 s->capacity = size;
 StackMakeEmpty(s);
 return s;
}
void StackMakeEmpty(STACK *s)
{
 s->topofstack = -1;
}
int StackIsEmpty(STACK *s)
{
 return s->topofstack == -1;
}
int StackIsFull(STACK *s)
{
 return s->capacity == (s->topofstack + 1);
}
int PushStack(STACK *s, const Type *x)
{
 if(StackIsFull(s))
  return -1;
 s->data[++s->topofstack] = *x;
 return 0;
}
int PosStack(STACK *s)
{
 if(StackIsEmpty(s))
  return -1;
 s->topofstack--;
 return 0;
}
int TopOfStack(STACK *s, Type *x)
{
 if(StackIsEmpty(s))
  return -1;
 *x = s->data[s->topofstack];
 return 0;
}
int TopAndPopStack(STACK *s, Type *x)
{
 if(!TopOfStack(s, x))
  return PosStack(s);
 return -1;
}
int DisposeStack(STACK *s)
{
 free(s->data);
 free(s);
}

上一篇:JDBC 程序实例小练习


下一篇:使用Django创建简易Blog