栈(stack)又名堆栈,它是一种运算受限的线性表。
栈有这样一种限制:插入和删除元素只能从一端操作,这一端被称为栈顶,相对地,把另一端称为栈底。
栈有两种基本操作:
1.插入操作:push;
2.删除操作:pop。
还有其他典型的操作:
3.返回栈顶:TOP;
4.判断栈是否为空:ISEMPTY;
Ⅰ数组实现:
1.
#define MAX_SIZE 101
int a[MAX_SIZE];
int top=-1;
为了方便先定义全局数组和栈顶top:
2.push(x)函数:
void push(int x)
{
if(top==MAX_SIZE-1)
{
printf("the stack overflow!");
return ;
}
top++;
a[top]=x;
}
如果栈溢出就输出提示语句然后返回,没有溢出则使top自加然后给数组中的top元素赋值x。
3.pop()函数:
void pop()
{
if(top==-1)
{
printf("no element to pop!");
return ;
}
top--;
}
如果栈空就输出提示语句然后返回,非空则只使top自减即可,因为下一次调用push函数时赋的值会覆盖需要删除的值。
4.TOP()函数:
int TOP()
{
return a[top];
}
没啥解释的,直接返回值。
5.ISEMPTY()函数:
int ISEMPTY()
{
if(top==-1)
printf("tha stack is empty");
else
printf("the stack is not empty");
}
这个也没啥解释的。
化零为整:
#include<stdio.h>
#define MAX_SIZE 101
int a[MAX_SIZE];
int top=-1;
void push(int x)
{
if(top==MAX_SIZE-1)
{
printf("the stack overflow!");
return ;
}
top++;
a[top]=x;
}
void pop()
{
if(top==-1)
{
printf("no element to pop!");
return ;
}
top--;
}
int TOP()
{
printf("the stack top_element is:");
return a[top];
}
int ISEMPTY()
{
if(top==-1)
printf("tha stack is empty");
else
printf("the stack is not empty");
}
void print()
{
int i;
printf("the stack is:");
for(i=0;i<=top;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
int main()
{
push(1);print();
push(2);print();
push(3);print();
push(4);print();
pop();print();
printf("%d\n",TOP());
ISEMPTY();
return 0;
}
瞅一眼结果:
Ⅱ链表实现:
PS:因为链表从尾部插入删除的时间复杂度是O(n),不符合栈的特点(O(1)),
所以我们选择从链表头部插入删除。
1.
typedef struct node{
int data;
struct node* next;
}sn;
sn* top=NULL;
2.push(x):
void push(int x)
{
sn* temp=(sn*)malloc(sizeof(sn));
temp->data=x;
temp->next=top;
top=temp;
}
3.pop():
void pop()
{
sn* p=top;
if(top==NULL)return ;
top=p->next;
free(p);
}
4.TOP():
int TOP()
{
sn* temp=top;
printf("the stack top_element is:");
return temp->data;
}
5.ISEMPTY():
int ISEMPTY()
{
if(top->next==NULL)
return 1;
else return 0;
}
化零为整:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* next;
}sn;
sn* top=NULL;
void push(int x)
{
sn* temp=(sn*)malloc(sizeof(sn));
temp->data=x;
temp->next=top;
top=temp;
}
void pop()
{
sn* p=top;
if(top==NULL)return ;
top=p->next;
free(p);
}
void print()
{
sn* p=top;
printf("the stack is:");
while(p!=NULL)
{
printf("%d ",p->data );
p=p->next;
}
printf("\n");
}
int TOP()
{
sn* temp=top;
printf("the stack top_element is:");
return temp->data;
}
int ISEMPTY()
{
if(top->next==NULL)
return 1;
else return 0;
}
int main()
{
push(2);print();
push(4);print();
push(6);print();
pop();print();
printf("%d\n",TOP());
if(ISEMPTY())
printf("the stack is empty");
else
printf("the stack is not empty");
}
瞅一眼结果:
从某种程度上来说:使用链表实现栈的方式更优雅~