您的位置:首页 > 理论基础 > 数据结构算法

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

2015-10-09 21:50 543 查看
栈是限定仅在表尾进行插入和删除操作的线性表

——先进后出

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

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

代码实现:

#include<stdio.h>
#include<malloc.h>
typedef int elementtype;//elementtyoe为数据类型的实际类型,这里设置为int
typedef 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;//把分配的空间的数据域设置为newdata
newNode->next = link->top;//把新结点的指针域指向原始栈的栈顶
link->count++;
link->top = newNode;//更新栈顶
}

void dele(Linkstack *link){//删除栈顶的结点
if(link->count > 0 ){//判断是否大于0
link->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;
}


顺序栈与链栈的时间复杂度是一样的,顺序栈的优势是存取时定位很方便,但是顺序栈事先需要一个固定的长度。链栈每个元素都有指针域,但对于栈的长度无限制。如果栈的使用过程中元素变化不可预料,最好用链栈实现,如果变化在可控范围内,建议使用顺序栈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: