栈的思想是先进后出,基于对链表的各种操作的理解,先进后出的操作可以看作链表的头插法以及从头部进行删除节点的操作,需要注意的是在出栈的操作时需要先判定栈是否为空。
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}Node;
struct Node* stackInit()
{
struct Node* head=(Node*)malloc(sizeof(Node));
head->data=0;
head->next=NULL;
}
void headInsert(Node* list,int data) //头插法入栈
{
struct Node* node=(Node*)malloc(sizeof(Node));
node->data=data;
node->next=list->next;
list->next=node;
list->data++;
}
int empty(Node* list) //判断栈是否为空
{
if(list->data!=0)
{
return 1;
}
else
{
printf("Empty!\n");
return 0;
}
}
int pop(Node* list) //出栈
{
if(empty(list)==0)
return 0;
else
{
Node* p=list->next;
int a=p->data;
list->next=p->next;
return a;
}
}
void print(Node* list)
{
Node* temp=list->next;
printf("List: ");
while(temp)
{
printf("%d--->",temp->data);
temp=temp->next;
}
printf("NULL\n");
}
int main(int argc,char *argv[])
{
int a;
Node * list=stackInit();
headInsert(list,1);
print(list);
headInsert(list,2);
print(list);
headInsert(list,3);
print(list);
a=pop(list);
printf("pop:%d \n",a);
print(list);
a=pop(list);
printf("pop:%d \n",a);
print(list);
a=pop(list);
printf("pop:%d \n",a);
print(list);
return 0;
}