栈_顺序/链式方式存储
栈(先进后出)
我们把生活中的栈的概念引入到计算机中,就是供数据休息的地方,它是一种数据结构,数据既可以进入到栈中, 又可以从栈中出去。
1、计算机中的栈
栈是一种基于先进后出(FILO)的数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出 的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一 个数据被第一个读出来)。 我们称数据进入到栈的动作为压栈,数据从栈中出去的动作为弹栈。
2、顺序存储的栈
先进后出:栈顶的位置会一直改变
2.1 栈的创建(malloc)
STACK *stack_create()
{
STACK *new;
new = malloc(sizeof(*new));
if(new == NULL)
return NULL;
new->top = -1; //top是栈内元素的下表 -1 代表空栈
return new;
}
typedef struct
{
int data[MAXSIZE];
int top;
}STACK;
2.2 压栈、出栈
int stack_push(STACK *ptr, const int *x)
{
if(stack_isfull(ptr))
return -1;
ptr->data[++ptr->top] = *x;
return 0;
}
int stack_pop(STACK *ptr, int *x)
{
if(stack_isempty(ptr))
return -1;
*x = ptr->data[ptr->top--]; //*x用来记录当前出栈的元素
return 0;
}
2.3 销毁
void stack_destroy(STACK *ptr)
{
free(ptr);
ptr = NULL;
}
2.4 main.c(部分)
int main()
{
STACK *st;
int a[] = {1,3,5,7,9,11,13};
int i,tmp;
// st = stack_create();
stack_create2(&st);
/*if error*/
for(i = 0 ; i < sizeof(a)/sizeof(*a); i++)
stack_push(st,&a[i]);
stack_display(st);
while(!stack_isempty(st))
{
stack_pop(st,&tmp);
printf("POP:%d\n",tmp);
}
stack_destroy(st);
exit(0);
}
3、链式存储的栈
带头结点的双向循环链表,只做第一个位置的插入和删除,压栈方式要选择首部插入_LLIST_FORWARD。
3.1 创建双向链表(malloc)
STACK *stack_create()
{
STACK *new;
new = malloc(sizeof(*new));
if(new == NULL)
return NULL;
new->prev = new;
new->next = new;
return new;
}
typedef struct stack_st
{
int data;
struct stack_st *prev,*next;
}STACK;
3.2 压栈、出栈
int stack_push(STACK *sta, const int *x)
{
STACK *new = sta;
//if(new->top == 6 - 1) return -1;
new = malloc(sizeof(*new));
if(new == NULL)
return -2;
new->data = *x;
new->prev = sta;
new->next = sta->next;
new->prev->next = new;
new->next->prev = new;
return 0;
}
int stack_pop(STACK *sta, int *x)
{
STACK *s = sta->next;
//if(stack_isempty(s) == 0) return -1;
*x = s->data;
s->prev->next = s->next;
s->next->prev = s->prev;
free(s);
return 0;
}
3.3 销毁
void llist_destroy(LLIST *ptr)
{
struct llist_node_st *cur,*next;
for(cur = ptr->next; cur != ptr ; cur = next)
{
next = cur->next;
free(cur);
}
free(ptr);
}
3.4 main.c(部分)
int main()
{
STACK *handler;
int i,ret;
int stu[] = {1,2,3,4,5,6};
handler = stack_create();
if(handler == NULL)
{
return -1;
printf("handler id eror \n");
}
for(i=0;i<sizeof(stu)/sizeof(*stu);i++)
{
stack_push(handler,&stu[i]);
}
int j=6;
//display(handler);
while(i)
{
stack_pop(handler,&ret);
printf("%d ",ret);
i--;
}
//stack_top(handler,&ret); //取栈顶元素查看,不出栈
//printf("\n%d\n",ret);
//display(handler);
exit(0);
}