一 概述
采用链式存储的栈成为链栈,链栈的优点是便于多个栈共享存储空间和提高效率,且不存在栈满上溢的情况。通常情况采用单链表实现,并规定所有的操作都是在单链表的表头进行的。
不含头结点的链栈,Lhead指向栈顶元素。
含头结点的链栈,头结点中只有指向链栈的指针,不含有元素。
二 链栈的链式存储类型描述
typedef struct Linknode{
ElemType data; //数据域
struct Linknode *next; //指针域
}*LinkStack; //栈类型定义
三 链栈操作细节
采用链式存储栈,便于结点的插入和删除。链栈的操作与链表类似,入栈和出栈的操作都在链表的表头进行。需要注意的是,对于带表头结点和不带表头结点的链栈,具体实现会有所区别。
四 链栈的代码实现
/**
*带头结点的链栈实现
**/
#include<stdio.h>
#include<cstdlib>
struct StackNode{
int data;
StackNode *next;
};
/*struct linkStack {
StackNode *top; //栈顶指针
int count; //计数器
};*/
//链栈的初始化,创建头结点
StackNode* initLinkStack() {
StackNode *head = (StackNode*)malloc(sizeof(StackNode));
if(head == NULL) {
printf("Allocate Memory failed.\n");
return NULL;
}
head->data = 0;
head->next = NULL;
return head;
}
//数据入栈
void Push(StackNode* head, int element) {
if(head == NULL) {
printf("The head node don't exist!");
return;
}
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
if(node == NULL){
printf("Error!");
return;
}
node->data = element;
node->next = head->next;
head->next = node;
}
//数据出栈
int Pop(StackNode* head) {
if(head == NULL||head->next == NULL) {
printf("Error!");
}
StackNode* temp = head->next;
head->next = temp->next;
int value = temp->data;
free(temp);
return value;
}
//栈的长度
int getLinkStackLength(StackNode* head){
if(head == NULL||head->next == NULL) {
return 0;
}
int length = 0;
StackNode* p = head->next;
while(p != NULL) {
length++;
p = p->next;
}
return length;
}
int main() {
StackNode* head = NULL;
printf("initStack");
head = initLinkStack();
Push(head, 3);
Push(head, 2);
Push(head, 1);
printf("output the length of the stack:");
printf("%d\n",getLinkStackLength(head));
printf("%d\n",Pop(head));
printf("%d\n",Pop(head));
printf("output the length of the stack:");
printf("%d\n",getLinkStackLength(head));
printf("%d\n",Pop(head));
printf("output the length of the stack:");
printf("%d\n",getLinkStackLength(head));
return 0;
}
代码结果