九层之台起于垒土,千里之行始于足下!
数据结构 顺序线性表
这个要注意的地方就是线性表中元素编号是从1开始的,但实际储存时却是用相当于数组的方式储存的,元素从0开始储存
故可以边画图边理解,下图标上“(reason)”的地方均是这个原因
#include<stdio.h> #include<string.h> #include<string> #include<iostream> #include<stdlib.h> #include<cmath> #define OK 1 #define ERROR 0 #define overFlow -2 #define increment 10//当空间不够时,要开辟新空间的增量 using namespace std; typedef int status; typedef int ElemType; typedef struct myList { ElemType *elem; int length;//当前线性表长度,也就是所含个数 int listsize;//当前线性表储存空间 } List; status initList(List &L) { L.elem=(ElemType*)malloc(increment*sizeof(int));//开辟新空间 if(L.elem==NULL) exit(overFlow); L.length=0; L.listsize=increment; return OK; } status hasElem(List L,int e) { int i,j; for(i=0; i<L.length; i++) { if(L.elem[i]==e)return i+1;//解释看文章开头(reason) } return ERROR; } status insertList(List &L,int i,int e) { int j,k; if(L.listsize==L.length)//看现在空间是否已经满了,如果满了,那就应该增加空间 { ElemType *tmp=(ElemType *)realloc(L.elem,(L.listsize+increment)*sizeof(int)); if(tmp!=NULL){L.elem=tmp; L.listsize+=increment; } else return ERROR; } if(i<1||i>L.length+1)return ERROR; j=0; for(j=L.length; j>=i; j--) L.elem[j]=L.elem[j-1];//(reason) L.elem[i-1]=e; L.length++; return OK; } status deleteList(List &L,int k) { int j; for(j=k-1; k<L.length-1; k++)//这里的删除并不是真正吧要删除的元素的空间释放掉 //而是直接用后一个数据覆盖前一个数据,达到“删除”的目的, L.elem[j]=L.elem[j+1];//(reason) L.length--; return OK; } status updataList(List &L,int i,int e) { if(i<1||i>L.length)return ERROR; L.elem[i-1]=e;//顺序线性表修改很容易 return OK; } status getelem(List L,int i){ if(i<1||i>L.length) return -1; else return L.elem[i-1]; } void traverseList(List L) { int i,j; for(i=0; i<L.length; i++)//因为是顺序线性表遍历也容易 printf("%d ",L.elem[i]); puts(""); } int main() { int i,j,n,temp; scanf("%d",&n); List L; initList(L); for(i=1; i<=n; i++) { scanf("%d",&temp); insertList(L,i,temp); } printf("*%d %d* ",L.length,L.listsize); traverseList(L); insertList(L,3,55); insertList(L,5,99); insertList(L,1,100); printf("*%d %d* ",L.length,L.listsize); traverseList(L); deleteList(L,2); deleteList(L,6); printf("*%d %d* ",L.length,L.listsize); traverseList(L); updataList(L,4,10); updataList(L,2,11); printf("*%d %d* ",L.length,L.listsize); traverseList(L); if(temp=hasElem(L,55))printf("Has this elem,it is the %dth number! ",temp); else printf("don't have this elem! "); insertList(L,L.length+1,55); if(temp=hasElem(L,55))printf("Has this elem,it is the %dth number! ",temp); else printf("don't have this elem! "); printf("%d*%d ",getelem(L,5),L.listsize); return 0; } /* 5 1 2 3 4 5 */