链栈的实现方式,使用头插法的方式进行实现,每次从头插入的过程就是入栈的过程。 链栈的结构体
typedef struct StackNode
{
int data;
struct StackNode *next;
}StackNode,*LinkStack;
Push():将数据入栈
void Push(StackNode *s ,int data)
{
StackNode *p = (StackNode *) malloc(sizeof(StackNode));
p->data = data ;
p->next = s->next;
s->next = p;
printf("push data is %d \n ",s->next->data);
}
Pop(),将数据出栈,并删除那个节点
void Pop(StackNode *s,int *data)
{
if(s->next != NULL)
{
*data = s->next->data;
s->next = s->next->next;
}
else{
printf("stack is empty \n");
}
}
PrintfStack(),遍历整个链栈
void Pop(StackNode *s,int *data)
{
if(s->next != NULL)
{
*data = s->next->data;
s->next = s->next->next;
}
else{
printf("stack is empty \n");
}
}
整个程序
#include<stdio.h>
#include<stdlib.h>
typedef struct StackNode
{
int data;
struct StackNode *next;
}StackNode,*LinkStack;
StackNode *InitStack()
{
StackNode *s = (StackNode *) malloc(sizeof(StackNode));
if(s == NULL)
{
printf("create fail \n");
return 0;
}
s->next = NULL;
return s;
}
void Push(StackNode *s ,int data)
{
StackNode *p = (StackNode *) malloc(sizeof(StackNode));
p->data = data ;
p->next = s->next;
s->next = p;
printf("push data is %d \n ",s->next->data);
}
void Pop(StackNode *s,int *data)
{
if(s->next != NULL)
{
*data = s->next->data;
s->next = s->next->next;
}
else{
printf("stack is empty \n");
}
}
void PrintfStack(StackNode *s)
{
while(s->next != NULL)
{
printf("%d\n",s->next->data);
s = s->next ;
}
}
int main()
{
int i,j,data=0;
StackNode *Stack = InitStack();
for(i = 0 ; i< 10 ; i++)
{
Push(Stack,i);
}
for(j =0 ; j<10; j++)
{
Pop(Stack , &data);
printf("pop data is %d \n ",data);
}
}
运行结果
|