栈有头节点,头节点后就是栈顶,即执行push操作时,插在头节点后;
可以把弹出的元素放在另一个栈中;
//栈的单链表实现
#include <stdio.h>
struct node
{
int element;
struct node* next;
} ;
void Push(struct node* stack,int element)//栈头在stack后,即push在stack后
{
struct node* s;
s=(struct node*)malloc(sizeof(struct node));
s->element=element;
s->next=stack->next;
stack->next=s;
}
void Pop(struct node* stack)
{
struct node* temp;
temp->next=stack->next;
stack->next=temp->next;
free(temp);
}
void Top(struct node* stack)
{
if(stack->next==NULL){
printf("The stack is empty!\n");
return;
}
printf("%d\n",stack->next->element);
}
int main()
{
//栈的新建
struct node* stack;//表头
stack->next=NULL;
//Push
Push(stack,10);
//Pop
Pop(stack);
//Top
Top(stack);
return 0;
}