含表头的栈ADT(C语言版)

本文介绍了如何使用C语言实现一个带有表头的栈抽象数据类型(ADT)。通过定义一个结构体,其中包含指向栈顶元素的指针,实现了对栈的操作。栈顶元素可以通过S->next->element进行访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表头S为指针,指向一个结构体,S->next表示S指向的结构体中的结构的next域,这个next存储的是栈顶的地址,所以S->next表示栈顶地址,所以S->next->element表示栈顶的元素中的值。

具体代码如下:

#ifndef MYSTACK_H_
#define MYSTACK_H_
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h> 
struct Node;
typedef struct Node * Stack; //用于声明指向表头的指针 
typedef struct Node * PtrToNode; //用于声明指向结构体(节点)的指针 
typedef int ElementType;

struct Node
{
	ElementType element;
	PtrToNode next;//前一个节点(元素)地址 
};

//函数声明 
Stack InitStack(void);//创建一个空栈,返回表头地址 
bool IsEmpty(Stack S); //判断是否为空 空返回true
Stack Pop(Stack S);// 出栈 返回新栈顶地址
void ClearStack(Stack S); //清空栈 变为空栈 
int StackLength(Stack S); //返回栈中元素数目 
ElementType GetTop(Stack S);//返回栈顶的值
Stack Push(ElementType E, Stack S);// 入栈 返回新栈顶地址 

//函数实现
Stack InitStack(void)
{
	Stack tempNode;
	tempNode = (PtrToNode)malloc(sizeof(struct Node));
	if(tempNode == NULL)
		printf("Out of space!\n");
	tempNode -> next = NULL;
	return tempNode;
}

bool IsEmpty(Stack S)
{
	return S -> next == NULL;
}

Stack Pop(Stack S)
{
	PtrToNode tempNode; 
	if(IsEmpty(S)){
		printf("Stack is empty\n");
		return S;
	}
	else{
		tempNode = S -> next;
		S -> next = S -> next -> next; //S为表头地址,表头的next存的是栈顶的地址 
		free(tempNode); //栈底元素的next为NULL 所以在删除最后一个元素后 
		return S;       //S的next才为NULL 
	}
}

void ClearStack(Stack S)
{
	while(IsEmpty(S) != true)
		S = Pop(S);
}

int StackLength(Stack S)
{
	int sum = 0;
	while(IsEmpty(S) != true){
		S -> next = S -> next -> next;
		sum ++;
	}
	return sum;
}

ElementType GetTop(Stack S)
{
	if(IsEmpty(S)){
		printf("Stack is empty\n");
		return 0; //返回值防止编译器报错 
	}
	else 
		return S -> next -> element;
}

Stack Push(ElementType E, Stack S)
{
	PtrToNode tempNode;
	tempNode = (PtrToNode)malloc(sizeof(struct Node));
	if(tempNode == NULL){
		printf("Out Of Space!\n");
		return tempNode;
	}
	else{
		tempNode -> next = S -> next;
		tempNode -> element = E;
		S -> next = tempNode;
		return S;
	}
}

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值