栈遵从后入先出原则,而链表的内存大小是不确定的,动态分配,并且链表的唯一入口是头节点指针,因此要想用链表实现栈,我们只需要在链表的头节点或者尾节点插入或者删除新增节点这样就可以实现栈的功能。
struct node
{
int data;
node *=link;
}
struct node* top=NULL;
int push(int x)//用于压栈
{
struct node* temp=(struct node* )malloc(sizeof(struct node));//开辟内存空间分配一个头节点
temp->data=x;
temp->link=top;
top= temp;
}
int pop()//用于栈的弹出
{
struct node* temp;//用于记录并删除压出节点和数据
if(top==NULL)
{
return;
}
temp=top;
top=top->link;
free(temp);
}