天天看点

数据结构-栈的链式存储

目标效果:

数据结构-栈的链式存储

stack.h页面:

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

#ifndef ElemType
#define ElemType int /* 数据元素类型默认为 int */
#define ELEMTYPE_TAG
#endif

//链栈的存储结构定义
typedef struct LNode {
    ElemType data;
    struct LNode *next;
} LNode, *LinkList;

typedef LinkList LinkStack; //链栈类型
//链栈的基本操作声明

//构造一个空栈S
bool InitStack(LinkStack &S);
//销毁栈S
bool DestroyStack(LinkStack &S);
//将栈S清空
bool ClearStack(LinkStack &S);
//若栈S为空返回TRUE,否则FALSE
bool StackEmpty(LinkStack S);
//返回栈S中的元素个数
int    StackLength(LinkStack S);
//用e返回栈顶元素
//    前提:栈S存在且不空
bool GetTop(LinkStack S, ElemType &e);
//元素e入栈S
bool Push(LinkStack &S, ElemType e);
//S出栈用e返回出栈元素
//    前提:栈S存在且不空
bool Pop(LinkStack &S, ElemType &e);

///
//链栈的基本操作的实现

//构造一个空栈S
bool InitStack(LinkStack &S)
{
	S=NULL;
    return true;
}

//销毁栈S
bool DestroyStack(LinkStack &S)
{
	S=NULL;
    return true;
}

//将栈S清空
bool ClearStack(LinkStack &S)
{
	S->data;
    return true;
}

//若栈S为空返回TRUE,否则FALSE
bool StackEmpty(LinkStack S)
{
	if(S==NULL)
		return true;
	else
		return false;
}

//返回栈S中的元素个数
int    StackLength(LinkStack S)
{
	LinkStack L;
	L=S;
	int i=0;
	while(L)
	{
		L=L->next;
		i++;
	}
    return i;
}

//用e返回栈顶元素
//    前提:栈S存在且不空
bool GetTop(LinkStack S, ElemType &e)
{
	e=S->data;
    return true;
}

//元素e入栈S
bool Push(LinkStack &S, ElemType e)
{
	LinkStack P;
	P=(LinkList)malloc(sizeof(LNode));
	P->data=e;
	P->next=S;
	S=P;
	return true;
}

//S出栈用e返回出栈元素
//    前提:栈S存在且不空
bool Pop(LinkStack &S, ElemType &e)
{
	e=S->data;
	S=S->next;
	return true;
}


#ifdef ELEMTYPE_TAG
#undef ElemType
#undef ELEMTYPE_TAG
#endif

#endif

           

dsp0301.cpp页面:

#include <stdio.h>
#include <stdlib.h> )
#include "stack.h" //链栈

//测试链栈的主程序
int main()
{
    LinkStack s;
    int x;
    //输入若干正整数以0结束,依次入栈,然后依次出栈并打印
    InitStack(s);

    printf("输入若干正整数以0结束:");
    scanf("%d",&x);
    while(x!=0) {
        Push(s,x);
        scanf("%d",&x);
    }

	printf("\n栈中元素个数:");
	printf("%d",StackLength(s));

	printf("\n栈顶元素:");
	GetTop(s,x);
	printf("%d",x);

    printf("\n出栈结果:");
    while(!StackEmpty(s)) {
        Pop(s,x);
        printf("%4d",x);
    }

	printf("\n栈中元素个数:");
	printf("%d\n",StackLength(s));

    DestroyStack(s); //销毁栈

    system("PAUSE");
    return 0;
}
           

源码下载:点击打开链接

继续阅读