栈是一种特殊的线性表
它只能在一端进行进行操作,因而存取的元素有先进后出的特点
头插法相同
操作:
1.初始化栈
2.出栈
3.入栈
4.判断栈空
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* initstack()
{
Node* head=(Node*)malloc(sizeof(Node));
head->next=NULL;
head->data=0;
}
int is_empty(Node* head)
{
if(head->next==NULL||head->data==0)
{
return 1;
}
else
{
return 0;
}
}
int get_top(Node* head)
{
if(is_empty(head))
{
return -1;
}
else
{
return head->next->data;
}
}
int pop(Node* head)
{
if(is_empty(head))
{
return -1;
}
else
{
Node* node=(Node*)malloc(sizeof(Node));
node=head->next;
int data=node->data;
head->next=node->next;
free(node);
return data;
}
}
void push(Node* head,int data)
{
Node* node=(Node*)malloc(sizeof(Node));
node->data=data;
node->next=head->next;
head->next=node;
head->data++;
}
void print_stcak(Node* head)
{
Node* node=(Node*)malloc(sizeof(Node));
node=head->next;
while(node!=NULL){
printf("%d->",node->data);
node=node->next;
}
printf("NULL");
}
int main()
{
Node* s=initstack();
push(s,1);
push(s,2);
push(s,3);
is_empty(s);
print_stcak(s);
printf("\n");
int i=pop(s);
printf("top为%d\n",i);
print_stcak(s);
return 0;
}