数据结构之栈的链式存储结构

来源:互联网 发布:js 获取http 的状态 编辑:程序博客网 时间:2024/05/29 03:21

栈是限定仅在表尾进行插入和删除操作的线性表


——先进后出

 应用:浏览器的后退键,或者撤销操作
     允许插入和删除的一端称为栈顶,另一端称为栈底;不含任何数据匀速的栈称为空栈。栈又称为后进先出(last in first out,)线性表,简称LIFO结构
     栈的插入操作,叫做进栈,也称压栈、入栈。
     栈的删除操作,叫做出栈,也叫做弹栈

栈的链式存储结构——链栈

代码实现:

#include<stdio.h>#include<malloc.h>typedef int elementtype;//elementtyoe为数据类型的实际类型,这里设置为inttypedef struct node {elementtype data;//结点数据域中的数据struct node *next;//链栈中指向下面的那个结点}Node; struct Linkstack{node *top;//指向栈顶的指针int count;//链栈的结点个数};    void create(Linkstack *link){//创建栈puts("please input numbers,quite with not a number");Node *node = (Node *)malloc(sizeof(Node));while((scanf("%d",&node->data)) == 1){//当不是输入的数字时退出if(link->count == 0){//当第一个结点node->next = NULL;//其指针域为空;这里和链表反向link->top = node;link->count++;}else{link->count++;node->next = link->top;//把后进来的指针域指向上一个结点位置link-> top = node;//把新进来的结点设置为栈顶puts("please input numbers,quite with not a number");node = (Node *)malloc(sizeof(Node));}}}void print(Linkstack *link){Node *output = link->top;int i;for(i = 0 ;i < link->count;i++){printf("%d\t",output->data);output = output->next;}puts("");}void push(Linkstack *link,elementtype newdata){//在栈链中添加新结点Node *newNode = (Node*)malloc(sizeof(Node));//分配对应的空间newNode->data = newdata;//把分配的空间的数据域设置为newdatanewNode->next = link->top;//把新结点的指针域指向原始栈的栈顶link->count++;link->top = newNode;//更新栈顶}void dele(Linkstack *link){//删除栈顶的结点if(link->count > 0 ){//判断是否大于0link->top = link->top->next;//把栈顶对象改成第二个link->count--;}}int main(){Linkstack linkedstack,*linkstack;//声明一个栈链,指向栈链的指针linkstack = &linkedstack;linkstack->count = 0;create(linkstack);print(linkstack);push(linkstack , 7);print(linkstack);dele(linkstack);print(linkstack);return 0;}





顺序栈与链栈的时间复杂度是一样的,顺序栈的优势是存取时定位很方便,但是顺序栈事先需要一个固定的长度。链栈每个元素都有指针域,但对于栈的长度无限制。如果栈的使用过程中元素变化不可预料,最好用链栈实现,如果变化在可控范围内,建议使用顺序栈

0 0
原创粉丝点击