一、栈的定义
从数据结构角度看,栈也是线性表,其特殊性在于栈的基本操作都是线性操作的子集,它是操作受限的线性表。
栈(stack)是限定仅在表尾进行插入或删除操作的线性表。
栈一般分为两种:
静态栈:用数组实现;
动态栈:用链表实现。
一般用的比较多的都是动态栈。如果学会了链表,其实对栈的操作就比较简单了。
二、栈的结构
空栈的结构:(其实就是栈顶和栈顶都指向一个不存放有效数据的头结点)
存有结点的栈结构:(栈顶指针指向栈顶结点,栈底指针指向头结点)
三、用C语言实现
/* 2016年9月17日11:35:35 栈的操作和算法 */ #include <stdio.h> #include <malloc.h> #include <stdlib.h> typedef struct Node { int data; //数据域 struct Node * pNext; //指针域 } NODE, * PNODE; typedef struct Stack { PNODE pTop; //栈顶 PNODE pBottom; //栈底 } STACK, * PSTACK; //函数声明 void init_stack(PSTACK pS); //初始化栈 void push_stack(PSTACK pS, int val); void traverse_stack(PSTACK pS); bool is_empty(PSTACK pS); bool pop_stack(PSTACK pS, int * pVal); void clear_stack(PSTACK pS); int main(void) { STACK S; int val; init_stack(&S); push_stack(&S, 1); push_stack(&S, 2); push_stack(&S, 3); push_stack(&S, 4); push_stack(&S, 5); traverse_stack(&S); clear_stack(&S); traverse_stack(&S); /* if(pop_stack(&S, &val)) { printf("出栈成功,出栈的值为:%d\n",val); } else { printf("出栈失败,栈为空!\n"); } traverse_stack(&S); */ return 0; } void init_stack(PSTACK pS) //初始化栈 { PNODE pNew = (PNODE)malloc(sizeof(NODE)); //造出一个栈的头结点 if(NULL == pNew) { printf("内存分配失败,程序终止!\n"); exit(-1); } pS->pTop = pNew; pS->pBottom = pS->pTop; pNew->pNext = NULL; } void push_stack(PSTACK pS, int val) //压栈 { PNODE pNew = (PNODE)malloc(sizeof(NODE)); if(NULL == pNew) { printf("内存分配失败,程序终止!\n"); exit(-1); } pNew->data = val; pNew->pNext = pS->pTop; //不能是pNew->pNext = pBottom;因为当有多个节点时,pTop不等于pBottom; pS->pTop = pNew; return; } void traverse_stack(PSTACK pS) //遍历输出,从栈顶开始遍历 { PNODE p = pS->pTop; while(pS->pBottom != p) { printf(" %d \n", p->data); p = p->pNext; } printf("\n"); return; } bool is_empty(PSTACK pS) //判断是否为空 { if(pS->pTop == pS->pBottom) return true; else return false; } bool pop_stack(PSTACK pS, int * pVal) //出栈 { if(is_empty(pS)) //先判断是否为空 { return false; } else { PNODE p = pS->pTop; *pVal = p->data; pS->pTop = p->pNext; free(p); p = NULL; return true; } } void clear_stack(PSTACK pS) //清空栈 { PNODE p, q; p = pS->pTop; q = NULL; while(pS->pBottom != p) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pBottom; return; }
原文:http://www.cnblogs.com/yzy-blogs/p/6011734.html