线性表--链栈(十一)

时间:2022-07-28
本文章向大家介绍线性表--链栈(十一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.介绍链栈

所谓链栈,就是用链表存储结构实现的栈。采用链栈,可以不事先估计栈的最大容量,只要系统有足够的空间,链栈就不会溢出,在使用完后,应与链表一样,给予相应的内存释放。

2.代码实现

(1)定义链栈

typedef struct node
{
 int data;
 struct node * next;
}Node;

(2)初始化

Node * InitStack()
{
 Node * Head = (Node *)malloc(sizeof(Node));
 Head->data = 0;
 Head->next = NULL;
 return Head;
}

(3)进栈

int Push(Node * top, int x)
{
 Node * temp;
 temp = (Node *)malloc(sizeof(Node));
 if (temp == NULL)return(false);
 temp->data = x;
 temp->next = top->next;
 top->next = temp;
 return(true);
}

(4)出栈

int Pop(Node * top, int *x)
{
 Node * temp;
 temp = top->next;
 if (temp == NULL)return(false);
 top->next = temp->next;
 *x = temp->data;
 free(temp);
 return(true);
}

好了,这就是链栈。

若有错误,欢迎指正批评,欢迎讨论。 每文一句:人生是洁白的画纸,我们每个人就是手握各色笔的画师;人生也是一条看不到尽头的长路,我们每个人则是人生道路的远足者;人生还像是一块神奇的土地,我们每个人则是手握农具的耕耘者;但人生更像一本难懂的书,我们每个人则是孜孜不倦的读书郎。