天天看點

資料結構-棧的鍊式存儲

目标效果:

資料結構-棧的鍊式存儲

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;
}
           

源碼下載下傳:點選打開連結

繼續閱讀