线性表的静态链表存储结构
头文件
1 //SLinkList.h 2 3 #ifndef SLINKLIST_H 4 #define SLINKLIST_H 5 6 #define MAXSIZE 1000 7 8 typedef char ElemType; 9 typedef struct { 10 ElemType data; 11 int cur;//游标 12 }componet,SLinkList[MAXSIZE]; 13 14 int LocateElem(SLinkList S, ElemType e); 15 void InitSpace(SLinkList &space); 16 int Malloc(SLinkList &space); 17 void Free(SLinkList &space, int k); 18 void BuildSL(SLinkList &SL); 19 void AppendSL(SLinkList &SL, ElemType e, int k); 20 void TravelSL(SLinkList SL); 21 22 #endif
操作实现
//SLinkList.cpp #include"SLinkList.h" #include<iostream> int LocateElem(SLinkList S, ElemType e) //在静态单链表S中查找第1个值为e的元素 //若找到,则返回它在S中的次序,否则返回0 { int i = S[0].cur; //i指示表中的第一个结点 while (i&&S[i].data != e) i = S[i].cur; //在表中顺链查找 return i; } void InitSpace(SLinkList &space) //将一维数组space中各分量链成一个备用链表,space[0].cur为头指针,“0“表示空指针 { for (int i = 0; i < MAXSIZE - 1; i++) space[i].cur = i + 1; space[MAXSIZE - 1].cur = 0; } int Malloc(SLinkList &space) //若备用空间链表非空,则返回分配的结点下标,否则返回0 { int i = space[0].cur; if (space[0].cur) space[0].cur = space[i].cur; return i; } void Free(SLinkList &space,int k) //将下表为k的空闲结点回收到备用链表 { space[k].cur = space[0].cur; space[0].cur = k; } void BuildSL(SLinkList &SL) { SL[0].cur = 0; } void AppendSL(SLinkList &SL,ElemType e ,int k) //在位置k插入元素 { int i = SL[0].cur; while (SL[i].cur) i = SL[i].cur; SL[i].cur = k; SL[k].cur = 0; SL[k].data = e; } void TravelSL(SLinkList SL) { int i = SL[0].cur; while (i) { std::cout <<"SL["<<i<<"] = "<< SL[i].data << " "; i = SL[i].cur; } std::cout << std::endl; }
主函数实现
1 Main.cpp 2 3 #include"SLinkList.h" 4 #include<iostream> 5 using namespace std; 6 7 int main() 8 { 9 SLinkList space; 10 SLinkList SL; 11 InitSpace(space); 12 BuildSL(SL); 13 ElemType a = 'a'; 14 AppendSL(SL,a,5); 15 AppendSL(SL, a, 8); 16 TravelSL(SL); 17 system("pause"); 18 return 0; 19 }