C语言 之 栈

来源:互联网 发布:动态最优化课后题答案 编辑:程序博客网 时间:2024/06/08 00:43

后进先出的数据结构,先存入栈的底部,往上插入,最先插入的数据先出栈。

只能向顶部加,只能从顶部删

 

利用数组实现栈,数组放到结构体中,结构体中包括下标、总和、数组:下标初始化比正常数组多一,便于判断栈是否为空

创建栈:stack_t* create_stack()

{

      stack_t* s = (stack_t*)malloc(sizeof(stack_t));

      ERROR(s, NULL);

      s->top = SIZE;

      s->total = SIZE;

      memset(s->array, 0, sizeof(s->array));

      return s;

}

栈中插入数据:从栈底插入

int push_stack(stack_t* s, int data)

{

      ERROR(s, -1);

      STACK_FULL(s->top, -1); //判断栈是否满了

      s->top --;

      s->array[s->top] = data;

      return 0;

}

栈里取值

int pop_stack(stack_t* s, int* data)//利用型参保存取出的数据,传址类型

{

      ERROR(s, -1);

      STACK_EMPTY(s->top, -1); //是否为空,空的不许要取值

      *data = s->array[s->top];

      s->array[s->top] = 0; //取出后置零

      s->top ++; //退入下一个位置

      return 0;

}

判断栈是否为空:

int full_stack(stack_t* s)

{

      ERROR(s, -1);

      STACK_FULL(s, 1);

      return 0;

}

 

int empty_stack(stack_t* s)

{

      ERROR(s, -1);

      STACK_EMPTY(s, 1);

      return 0;

}

 

利用链表实现栈:

创建栈:stack_l* stack_create(int size)

[root@Abel stack_l]# cat stack_l.c

#include "stack_l.h"

stack_l* stack_create(int size)

{

      stack_l* s = (stack_l*)malloc(sizeof(stack_l));

      ERROR(s, NULL);

      s->top = 0;

      s->total = size;

      s->head = create_list();

      return s;

}

[root@Abel stack_l]# cat list.c

#include"list.h"

node* create_list()

{

      node* head = (node*) malloc(sizeof(node));

      if(NULL == head)

      {

           printf("NULL\n");

           exit(1);

      }

      head->data = 0;

      head->next = NULL

      return head;

}

向栈里插入数据:int push_stack(stack_l* s, int data)

{

      ERROR(s, -1);

      if(s->top == s->total) //栈是否满了

      {

           perror("stack is full\n");

           return -1;

      }

 

      insert_hlist(s->head, data); //list.c中的函数

      s->top ++; //指向下一个数组

      return 0;

}

遍历栈的数据:int show_stack(stack_l* s)

{

      ERROR(s, -1);

      if(s->top == 0)

      {

           perror("stack is empty\n");

           return -1;

      }

      find_alist(s->head); //list.c

      return 0;

}

删除战中数据:int pop_stack(stack_l* s, int *data)

{

      ERROR(s, -1);

      if(0 == s->top)

      {

           perror("stack is empty\n");

           return -1;

      }

      *data = s->head->next->data;//head中的下一个的数据

      delete_hlist(s->head);

      s->top —; //指向上一个

      return 0;

}

原创粉丝点击