数据结构---栈(指针实现)

本文介绍了使用C语言实现数据结构栈的方法,并提供了相应的源代码示例。

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

用C语言描述栈,以下是源代码:

#include "stack.h"

Stack CreatStack(void)
{
	PtrToNode S = (PtrToNode)malloc(sizeof(Node));
	if (S == NULL)
	{
		printf("Out of space!\r\n");
		return NULL;
	}
	S->Next = NULL;
	memset(&(S->Element), 0, sizeof(ElementType));
	return S;
}

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

bool MakeEmpty(Stack S)
{
	while (!IsEmpty(S))
	{
		Pop(S);
	}
	return false;
}
bool Push(Stack S, ElementType X)
{
	PtrToNode TmpCell;
	TmpCell = (PtrToNode)malloc(sizeof(Node));
	if (TmpCell == NULL)
	{
		printf("Out of space!\r\n");
		return false;
	}
	TmpCell->Element = X;
	TmpCell->Next = S->Next;
	S->Next = TmpCell;
	return true;
}
ElementType Top(Stack S)
{
	ElementType ret;
	memset(&ret, 0, sizeof(ElementType));
	if (IsEmpty(S))
	{
		printf("Empty Stack!\r\n");
		return ret;
	}
	return S->Next->Element;
}

bool Pop(Stack S)
{
	PtrToNode TmpCell;
	if (IsEmpty(S))
	{
		printf("Empty Stack!\r\n");
		return false;
	}
	TmpCell = S->Next;
	S->Next = S->Next->Next;
	free(TmpCell);
	return true;
}

bool PrintAllNode(Stack S)
{
	PtrToNode temp;
	temp = S;
	if (IsEmpty(temp))
	{
		printf("Empty Stack!\r\n");
		return false;
	}
	uint16_t ElementCnt = 0;
	while (!IsEmpty(temp))
	{
		printf("No %d element is: %c  %d\r\n", ++ElementCnt, temp->Next->Element.ch, temp->Next->Element.Index);
		temp = temp->Next;
	}
	printf("********   End   ********\r\n");
	return true;
}

#ifndef __STACK_H_
#define __STACK_H_

#include <stdbool.h>
#include <stdint.h>
#include <malloc.h>
#include <stdbool.h>
#include <stdio.h>
#include <memory.h>

typedef struct
{
	uint16_t Index;
	char ch;
}ElementType;
typedef struct node
{
	ElementType Element;
	struct node *Next;
}Node;
typedef Node *PtrToNode;
typedef PtrToNode Stack;

Stack CreatStack(void);
bool IsEmpty(Stack S);
bool MakeEmpty(Stack S);
bool Push(Stack S, ElementType X);
ElementType Top(Stack S);
bool Pop(Stack S);
bool PrintAllNode(Stack S);

#endif



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值