数据结构之链式栈(二)

链式栈

  • 1.链式栈,可以看作是链表的特殊操作
  • 2.链式栈用链表实现,同样满足先进后出

说明:

  • 本例采用带头节点的链表实现

示例:

#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;

typedef int SElemType;

struct LStack
{
	SElemType data;
	LStack *next;
};

typedef  LStack *LinkStack;

void InitStack(LinkStack &S)
{
	S = (LinkStack)malloc(sizeof(LStack));
	if (!S)
		return;
	S->next = NULL;
}

void DestoryStack(LinkStack &S)
{
	LinkStack q;
	while (S)
	{
		q = S->next;
		free(S);
		S = q;
	}
}

void ClearStack(LinkStack S)
{
	LinkStack p, q;
	p = S->next;
	while (p)
	{
		q = p->next;
		free(p);
		p = q;
	}
	S->next = NULL;
}

int StackEmpty(LinkStack S) {

	if (S->next)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}


int StackLength(LinkStack S) {
	int len = 0;
	LinkStack p = S->next;
	while (p)
	{
		len++;
		p = p->next;
	}
	return len;
}

int GetElem(LinkStack S, int i, SElemType &e) {
	int j = 1;
	LinkStack p = S->next;
	while (p && j<i)
	{
		p = p->next;
		j++;
	}
	if (!p || j > i)
		return 0;
	e = p->data;
	return 1;
}


int StackInsert(LinkStack S, int i, SElemType e) {
	int j = 0;
	LinkStack p = S, s;
	while (p&&j<i-1)
	{
		p = p->next;
		j++;

	}

	if (!p || j > i - 1)
		return 0;
	s = (LinkStack)malloc(sizeof(LStack));
	s->data = e;
	s->next = p->next;
	p->next = s;
	return 1;

}

int StackDelete(LinkStack S, int i, SElemType &e) {
	int j = 0;
	LinkStack p = S, q;
	while (p->next && j<i-1)
	{
		p = p->next;
		j++;
	}
	if (!p || j > i - 1)
		return 0;
	q = p->next;
	p->next = q->next;
	e = q->data;
	free(q);
	return 1;
}

void LTraverse(LinkStack S, void(*vi)(SElemType)) {
	LinkStack p = S->next;
	while (p)
	{
		vi(p->data);
		p = p->next;
	}
	printf("\n");
}

void print(SElemType e)
{
	printf("%d\n", e);
}



int GetTop(LinkStack S, SElemType &e)
{ // 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
	return GetElem(S, 1, e);
}

int Push(LinkStack &S, SElemType e)
{ // 插入元素e为新的栈顶元素
	return StackInsert(S, 1, e);
}

int Pop(LinkStack &S, SElemType &e)
{ // 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
	return StackDelete(S, 1, e);
}

void StackTraverse(LinkStack S, void(*vist)(SElemType)) {

	LinkStack temp, p = S->next;
	InitStack(temp);
	while (p)
	{
		Push(temp, p->data);
		p = p->next;
	}
	LTraverse(temp, vist);
}



int main()
{
	int j;
	LinkStack s;
	SElemType e;
	InitStack(s); // 初始化栈s
	for (j = 1; j <= 5; j++) // 将2,4,6,8,10入栈
	{
		Push(s, 2 * j);
	}
	printf("栈中的元素从栈底到栈顶依次为:\n");
	StackTraverse(s, print);
	Pop(s, e);
	printf("弹出的栈顶元素为%d\n", e);
	printf("栈空否: %d(1:空 0:否)\n", StackEmpty(s));
	GetTop(s, e);
	printf("当前栈顶元素为%d,栈的长度为%d\n", e, StackLength(s));
	ClearStack(s);
	printf("清空栈后,栈空否: %d(1:空 0:否),栈的长度为%d\n", StackEmpty(s), StackLength(s));
	DestoryStack(s);
  
}

posted @ 2020-08-28 10:52  flyingswallow  阅读(151)  评论(0编辑  收藏  举报