栈的链式存储结构

一 概述

采用链式存储的栈成为链栈,链栈的优点是便于多个栈共享存储空间和提高效率,且不存在栈满上溢的情况。通常情况采用单链表实现,并规定所有的操作都是在单链表的表头进行的。

不含头结点的链栈,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;
}

代码结果

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值