http://blog.csdn.net/sxhelijian/article/details/48463801
本文針對數據結構基礎系列網絡課程(3):棧和隊列中第4課時棧的鏈式存儲結構及其基本運算實現。
按照“0207將算法變程序”[視頻]部分建議的方法,建設自己的專業基礎設施算法庫。
鏈棧算法庫采用程序的多文件組織形式,包括兩個文件:?
?
1.頭文件:listack.h,包含定義鏈棧數據結構的代碼、宏定義、要實現算法的函數的聲明;
#ifndef LISTACK_H_INCLUDED
#define LISTACK_H_INCLUDEDtypedef char ElemType;
typedef struct linknode
{ElemType data; //數據域struct linknode *next; //指針域
} LiStack; //鏈棧類型定義void InitStack(LiStack *&s); //初始化棧
void DestroyStack(LiStack *&s); //銷毀棧
int StackLength(LiStack *s); //返回棧長度
bool StackEmpty(LiStack *s); //判斷棧是否為空
void Push(LiStack *&s,ElemType e); //入棧
bool Pop(LiStack *&s,ElemType &e); //出棧
bool GetTop(LiStack *s,ElemType &e); //取棧頂元素
void DispStack(LiStack *s); //輸出棧中元素#endif // LISTACK_H_INCLUDED
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
2.源文件:listack.cpp,包含實現各種算法的函數的定義
#include <stdio.h>
#include <malloc.h>
#include "listack.h"void InitStack(LiStack *&s) //初始化棧
{s=(LiStack *)malloc(sizeof(LiStack));s->next=NULL;
}void DestroyStack(LiStack *&s) //銷毀棧
{LiStack *p=s->next;while (p!=NULL){free(s);s=p;p=p->next;}free(s); //s指向尾結點,釋放其空間
}int StackLength(LiStack *s) //返回棧長度
{int i=0;LiStack *p;p=s->next;while (p!=NULL){i++;p=p->next;}return(i);
}bool StackEmpty(LiStack *s) //判斷棧是否為空
{return(s->next==NULL);
}void Push(LiStack *&s,ElemType e) //入棧
{LiStack *p;p=(LiStack *)malloc(sizeof(LiStack));p->data=e; //新建元素e對應的節點*pp->next=s->next; //插入*p節點作為開始節點s->next=p;
}bool Pop(LiStack *&s,ElemType &e) //出棧
{LiStack *p;if (s->next==NULL) //棧空的情況return false;p=s->next; //p指向開始節點e=p->data;s->next=p->next; //刪除*p節點free(p); //釋放*p節點return true;
}bool GetTop(LiStack *s,ElemType &e) //取棧頂元素
{if (s->next==NULL) //棧空的情況return false;e=s->next->data;return true;
}void DispStack(LiStack *s) //輸出棧中元素
{LiStack *p=s->next;while (p!=NULL){printf("%c ",p->data);p=p->next;}printf("\n");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
3.在同一項目(project)中建立一個源文件(如main.cpp),編制main函數,完成相關的測試工作。 例:
#include <stdio.h>
#include "listack.h"int main()
{ElemType e;LiStack *s;printf("(1)初始化鏈棧s\n");InitStack(s);printf("(2)鏈棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(3)依次進鏈棧元素a,b,c,d,e\n");Push(s,'a');Push(s,'b');Push(s,'c');Push(s,'d');Push(s,'e');printf("(4)鏈棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(5)鏈棧長度:%d\n",StackLength(s));printf("(6)從鏈棧頂到鏈棧底元素:");DispStack(s);printf("(7)出鏈棧序列:");while (!StackEmpty(s)){ Pop(s,e);printf("%c ",e);}printf("\n");printf("(8)鏈棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(9)釋放鏈棧\n");DestroyStack(s);return 0;
}