数据结构
顺序表学习
1、初始化顺序表
#include <stdio.h> #include <stdlib.h> #define InitSize 10 typedef struct{ int *data; int MaxSzie; int len; }sqlList; void InitList(sqlList &list){ list.data = (int*)malloc(InitSize*sizeof(int)); list.len = 0; list.MaxSzie =InitSize; } void IncreaseSzie(sqlList &list,int len){ int *p = list.data; list.data = (int*)malloc((list.MaxSzie+len)*sizeof(int)); for(int i = 0;i<list.len;i++){ list.data[i] = p[i]; } list.MaxSzie = list.MaxSzie+len; free(p); } bool sqlListInsert(sqlList &list,int i, int e){ if(i<1 || i>InitSize){ return false; } if(list.len > InitSize){ return false; } for(int j = list.len ; j>=i;j--){ list.data[j] = list.data[j-1]; } list.data[i-1] = e; list.len++; return true; } bool deletesqllist(sqlList &list,int i,int &e){ if(i<1 || i>InitSize){ return false; } for(int j = i;j<list.len;j++){ list.data[j-1] = list.data[j]; } e = list.data[i-1]; list.len--; } int main(void) { sqlList list; InitList(list); int e =-1; if(deletesqllist(list,3,e)){ printf("删除成功%d\n",e); }else{ printf("删除失败"); } return 0; }
顺序表的查找操作:
1按位查找
return list.data[i-1];
时间复杂度为O(n);
2按元素查找
for(int i = 0;i<list.len;i++){ if(list.data[i] == e){ return i+1; } }