線性表的存儲
2016-03-19 16:21
197 查看
#include<stdio.h> #include <stdlib.h> #define MAXSIZE 100000 #define ERROR -1 //先創建一個結構體 typedef int Position; typedef struct LNode *List; struct LNode { int Data[MAXSIZE]; int Last;//這個線性表的長度 }; /* 初始化 */ List MakeEmpty() { List L;//定義一個指針 L = (List)malloc(sizeof(struct LNode));//申請一塊空間 L->Last = -1;//沒有元素,为最後一個的位置 return L; } /* 查找 */ int Find( List L, int X ) { int i = 0; printf("X:%d,",X); while(i<= L->Last && L->Data[i]!= X ) i++; printf("i:%d,last:%d",i,L->Last); if ( i > L->Last ) return ERROR; /* 如果没找到,返回错误信息 */ else return i; /* 找到后返回的是存储位置 */ } //添加元素 bool Insert( List L, int X, int P ) { /* 在L的指定位置P前插入一个新元素X */ int i; if ( L->Last == MAXSIZE-1) { /* 表空间已满,不能插入 */ printf("满了"); return false; } if ( P<0 || P>L->Last+1 ) { /* 检查插入位置的合法性 */ printf("位置不合法"); return false; } for( i=L->Last; i>=P; i-- ) L->Data[i+1] = L->Data[i]; /* 将位置P及以后的元素顺序向后移动 */ L->Data[P] = X; /* 新元素插入 */ L->Last++; /* Last仍指向最后元素 */ return true; } //刪除元素 bool Delete( List L, int P ) { /* 从L中删除指定位置P的元素 */ Position i; if( P<0 || P>L->Last ) { /* 检查空表及删除位置的合法性 */ printf("位置%d不存在元素", P ); return false; } for( i=P+1; i<=L->Last; i++ ) L->Data[i-1] = L->Data[i]; /* 将位置P+1及以后的元素顺序向前移动 */ L->Last--; /* Last仍指向最后元素 */ return true; } int main(){ List L; int X;//元素 int P; int N;//輸入多少個元素 int i; //要用insert先添加啊,不添加last++怎麼會動,所以一直會是-1,查找不到,總之一定要last++動起來,錯了這個太白癡了【淚... L = MakeEmpty(); scanf("%d", &N); for(i=0;i<N;i++) { scanf("%d", &X); Insert(L, X, i); } scanf("%d", &X); P = Find(L, X); if ( P == ERROR ) printf("没找到"); else printf("在%d位置",P); scanf("%d", &P); Delete(L, P ); for(i=0;i<L->Last;i++) printf("%d ",L->Data[i]); }
相关文章推荐
- jQuery Ajax 使用 ($.ajax、$.post、$.get)
- LeetCode-reorder-list
- 在Android Studio中使用Jni
- mysql数据库常用语句3
- the comment lines of the blast tabular format
- CoreMotion 使用心得
- 第37讲项目1——位乘大于位和
- 第4周项目1(1)求最大公约数
- BZOJ 2822: [AHOI2012]树屋阶梯
- Android 中SharedPreference存储
- 第六届蓝桥杯题目练习-3
- 随机生成四则运算表达式02
- Android 导航
- Android 碎片 Fragment
- C/C++ 错题总结
- opencv 学习之 亮度检测
- 721学习法则
- 组合数取模模板
- 基于最小优先级队列构造哈夫曼树 Java
- 2016大连理工大学计算机考研复试