一、栈的基本概念
1、栈的定义
栈(Stack):是只允许在一端进行插入或删除的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。
栈顶(Top):线性表允许进行插入删除的那一端。
栈底(Bottom):固定的,不允许进行插入和删除的另一端。
空栈:不含任何元素的空表。
栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构
链表与栈
链表分为从头部插入和从尾部插入,而栈从栈顶进入然后从栈顶出来。如果从尾部插入再进行删除的话,时间复杂度为O(n),因为每一次插入删除都需要遍历一遍,而从头部插入则时间复杂度为O(1),
下面就是使用链表实现栈的一部分代码
struct Node{
int data;
struct Node *link;
};
struct Node *top=NULL;
void push(int x){
struct Node *temp=(struct Node*)malloc(sizeof(struct Node*));
temp->data=x;
temp->link=top;
top=temp;
}
void pop(){
struct Node *temp;
if(top==NULL)return ;
temp=top;
top=top->link;
free(temp);
}