c语言实现链栈
代码:
#include <stdio.h>
#include <malloc.h>
#define FALSE 0
#define TRUE 1
typedef int elem;
//链栈节点
typedef struct node
{
elem index;
struct node *next;
}LinkStackNode;
//链栈结构
typedef struct
{
LinkStackNode *top;
int length;
}LinkStack;
void InitStack(LinkStack *s)
{
s->top = NULL;
s->length = 0;
}
int IsEmpty(LinkStack *s)
{
if(s->length==0)
return TRUE;
else
return TRUE;
}
int Push(LinkStack *s,elem value)
{
LinkStackNode *tmp = (LinkStack*)malloc(sizeof(LinkStack));
if(tmp==NULL)
return FALSE;
tmp->index = value; //赋值
tmp->next = s->top;
s->top = tmp;
s->length++;
return TRUE;
}
int Pop(LinkStack *s)
{
if(IsEmpty(s)==TRUE)
return FALSE;
LinkStackNode *tmp = s->top;
s->top = tmp -> next;
s->length--;
free(tmp);
return TRUE;
}
void print(LinkStack *s)
{
LinkStackNode *tmp = s -> top;
while(tmp!=NULL)
{
printf("%d",tmp->index);
tmp = tmp->next;
}
printf("\n");
}
遇到的问题:
1. 指针指向的是地址
2. 画图
附上大佬图的链接 https://blog.csdn.net/z944733142/article/details/80573628