主要代碼:
/****************************************************
@title: 數據結構實驗
@name: <實驗3-1> 棧的鏈式存儲結構
@object:
[實驗目的]
採用鏈式存儲結構實現棧的基本操作
[實驗提示]
1. 在stack.h中實現棧的基本操作,
在鏈式存儲結構中可是省去頭結點。
2. 在dsp0301.cpp中編寫適當的代碼,進行測試
@include:
stack.h [*]
棧的鏈式實現
@usage:
請查看"TO-DO列表",根據要求完成代碼
@copyright: BTC 2004, Zhuang Bo
@author: Zhuang Bo
@date: 2004
@description:
*****************************************************/
//測試鏈棧的主程序
int main()
{
LinkStack s;
int x;
//輸入若干正整數以0結束,依次入棧,然後依次出棧並打印
InitStack(s);
printf("輸入若干正整數以0結束:");
scanf("%d",&x);
while(x!=0) {
Push(s,x);
scanf("%d",&x);
}
int y;
printf("\n棧頂的元素爲:%d",GetTop(s,y));
printf("\n現在棧中的元素個數:%d",StackLength(s));
Pop(s,x);
printf("\n刪除成功,刪除元素爲:%d",x);
printf("\n現在棧中的元素個數:%d",StackLength(s));
printf("\n現在棧中的元素");
printf("\n出棧結果:");
while(!StackEmpty(s)) {
Pop(s,x);
printf("%4d",x);
}
printf("\n現在棧中的元素個數:%d",StackLength(s));
//-------------------------------------
// TODO (
//-------------------------------------
DestroyStack(s); //銷燬棧
system("PAUSE");
return 0;
}
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
#include "ds.h" //for Status,OK ...
#ifndef ElemType
#define ElemType int /* 數據元素類型默認爲 int */
#define ELEMTYPE_TAG
#endif
typedef struct LNode {
ElemType data;
struct LNode *next;
} LNode, *LinkList;
typedef LinkList LinkStack;
Status InitStack(LinkStack &S);
Status DestroyStack(LinkStack &S);
Status ClearStack(LinkStack &S);
Status StackEmpty(LinkStack S);
int StackLength(LinkStack S);
Status GetTop(LinkStack S, ElemType &e);
Status Push(LinkStack &S, ElemType e);
Status Pop(LinkStack &S, ElemType &e);
Status InitStack(LinkStack &S)
{
S=(LinkStack)malloc(sizeof(LNode));
if(!S){
exit(0);
}
S->next=NULL;
return OK;
}
Status DestroyStack(LinkStack &S)
{
LinkStack p;
while(S->next){
p=S->next;
S->next=p->next;
free(p);
}
return ERROR;
}
Status ClearStack(LinkStack &S)
{
S->next=NULL;
return OK;
}
Status StackEmpty(LinkStack S)
{
if(!S->next){
return TRUE;
}
return FALSE;
}
int StackLength(LinkStack S)
{
LinkStack p;
int j=0;
p=S;
while(p->next){
j++;
p=p->next;
}
return j;
}
Status GetTop(LinkStack S, ElemType &e)
{
if(!S){
return ERROR;
}
e=S->data;
return e;
}
Status Push(LinkStack &S, ElemType e)
{
LinkStack p=(LinkStack)malloc(sizeof(LNode));
p->data=e;
p->next=S;
S=p;
return OK;
}
Status Pop(LinkStack &S, ElemType &e)
{
LinkStack p;
if(!S){
return ERROR;
}
e=S->data;
p=S;
S=S->next;
free(p);
return OK;
}
#ifdef ELEMTYPE_TAG
#undef ElemType
#undef ELEMTYPE_TAG
#endif
#endif
演示結果: