堆栈的链式存储实现

堆栈的链式存储实现

栈的链式存储结构实际上就是一个单链表,叫作链栈。插入和删除操作只能在链栈的栈顶进行。 栈顶指针Top应该在链表的头部

数据结构:

typedef struct SNode *Stack;
struct SNode{
	ElementType Data;
	struct SNode *Next;
};

步骤(1) 堆栈初始化(建立空栈)
(2)判断堆栈S是否为空

Stack CreateStack()
{     /*构建一个堆栈的头结点,返回指针*/
	Stack S;
	S = (Stack)malloc(sizeof(struct SNode));
	S -> Next = NULL;
	return S;
}

(2)判断是否为空

int IsEmpty(Stack s)
{
	/* 判断堆栈S是否为空,若为空函数返回整数1,否则返回0*/
	return (S -> Next == NULL);

}

(3)将数据元素压入栈中

void Push(ElementType item, Stack S){
	/*  将元素item压入堆栈 S  */
	struct SNode *TmpCell;
	TmpCell = (struct SNode *)malloc(sizeof (struct SNode));
	TmpCell -> Element = item;
	TmpCell -> Next = S -> Next;
	S -> Next = TmpCell;
}
//链表不需要判别是否满了
ElementType Pop(Stack S)
{  /* 删除并返回堆栈S的栈顶元素  */
	struct SNode *FirstCell;
	ElementType TopElem;
	if( IsEmpty(S) )  {
		printf("堆栈空")return NULL}else{

		FirstCell = S-> Next;
		S->Next = FirstCell -> Element;
		free(FirstCell);
		return TopElem;

	}

}
发布了28 篇原创文章 · 获赞 3 · 访问量 1893

猜你喜欢

转载自blog.csdn.net/qq_44045101/article/details/104069285