zoukankan      html  css  js  c++  java
  • 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 ", x);
     PosStack(s);
     TopOfStack(s, &x);
     printf("x = %d ", 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);
    }

  • 相关阅读:
    js简单地发送一个请求
    浏览器缓存知识归纳
    文本选择问题: css & js
    闭包和重写函数 返回IE浏览器版本号
    新项目启动 考虑问题
    Angular 单元格合并
    pointer-events 使用场景
    移动开发 新建空白页面
    CSS Tip
    垂直居中方法
  • 原文地址:https://www.cnblogs.com/riskyer/p/3356233.html
Copyright © 2011-2022 走看看