YAZONG 我的开源

(数据结构)第二讲-线性结构(2.2.X:堆栈的定义与操作-顺序与链式存储C源码)

  , ,
0 评论0 浏览

C语言代码 : 堆栈的定义与操作-顺序存储

#include<stdio.h>
int main(void){
	return 0;
}
typedef int Position;
struct SNode{
	//存储元素的数组
	ElementType *Data;
	//栈顶指针
	Position Top;
	//堆栈最大容量
	int MaxSize;
}
typedef struct SNode *Stack;
Stack CreateStack(int MaxSize){
	Stack S = (Stack)malloc(sizeof(struct SNode));
	S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
	S->Top = -1;
	S->MaxSize = MaxSize;
	return S;
}
bool isFull(Stack S){
	return (S->Top == S->MaxSize - 1);
}
bool Push(Stack S,ElementType X){
	if(isFull(S)){
		printf("堆栈满");
		return false;
	}else{
		S->Data[++(S->Top)] = X;
		return true;
	}
}
bool isEmpty(Stack S){
	return (S->Top == -1);
}
ElementType Pop(Stack S){
	if(isEmpty(S)){
		printf("堆栈空");
		return ERROR;
	}else{
		return (S->Data[(S->Top)--]);
	}
}

C语言代码 : 堆栈的定义与操作-链式存储

#include<stdio.h>
int main(void){
	return 0;
}
typedef struct SNode *PtrToSNode;
struct SNode{
	ElementType Data;
	PtrToSNode Next;
}
typedef PtrToSNode Stack;
Stack CreateStack(){
	//构建一个堆栈的头结点,返回该结点的指针.
	Stack S;
	S = (Stack)malloc(sizeof(struct SNode));
	S->Next = NULL;
	return S;
}
bool isEmpty(){
	//判断堆栈是否为空
	return (S->Next == NULL);
}
bool Push(Stack S,ElementType X){
	//将元素X压入堆栈S
	PtrToSNode TmpCell;
	TmpCell = (PtrToSNode)malloc(sizeof(struct SNode));
	TmpCell->Data = X;
	TmpCell->Next = S->Next;
	S->Next = TmpCell;
	return true;
}
ElementType Pop(Stack S){
	//删除并返回堆栈S的栈顶元素
	PtrToSNode FirstCell;
	ElementType TopElem;
	if(isEmpty(S)){
		printf("堆栈空");
		return ERROR;
	}else{
		FirstCell = S->Next;
		TopElem = FirstCell->Data;
		S->Next = FirstCell->Next;
		free(FirstCell);
		return TopElem;
	}
}

标题:(数据结构)第二讲-线性结构(2.2.X:堆栈的定义与操作-顺序与链式存储C源码)
作者:yazong
地址:https://blog.llyweb.com/articles/2023/08/15/1692030624898.html