顺序结构实现线性表的基本操作
2015-09-06 08:33
609 查看
<pre name="code" class="cpp"> #include <stdio.h> #include <stdlib.h> typedef int Elementype; #define maxsize 10 typedef struct { Elementype data[maxsize]; int last; }List; int find (Elementype x,List *ptr) { int i=1; while (i<ptr->last && ptr->data[i]!=x) ///从i=1开始不断往后查找 i++; if (i>ptr->last) { printf ("Not found\n"); return -1; } else printf("The element you want to find in List is %dth\n",i); return 0; } void Insert (Elementype x,int i,List *ptr) { int j; if (ptr->last==maxsize) { printf ("List is full!\n"); return; } if (i<1 || i>ptr->last+2) { printf ("Error:i\n"); return; } for (j=ptr->last;j>=i;j--) ptr->data[j+1]=ptr->data[j]; ///将data[i+1]~data 向后移 ptr->data[i]=x; ptr->last++; return; } void Delete (int i,List *ptr) { int j; if (i<1 || i>ptr->last+1) ///检查空表及删除位置的合法性 { printf ("Not found %dth element\n",i); return; } for (j=i+1;j<=ptr->last;j++) ptr->data[j-1]=ptr->data[j]; ///将data[i+1]~data 向前移 ptr->last--; return; } void Scanf_List (List *p) ///输入单链表数据 { int i; for (i=1;i<=p->last;i++) scanf ("%d",&p->data[i]); } void Printf_List (List*p) ///遍历单链表 { int i; for (i=1;i<=p->last;i++) printf ("%d ",p->data[i]); printf ("\n"); } int main () { List n; printf ("Please input the lenth of List:\n"); scanf("%d",&n.last); printf ("Please input elements of List:\n"); Scanf_List(&n); Printf_List(&n); while (1) { int m; printf ("Please choose the operate\n"); printf ("1:Find\n2:Insert\n3:Delet\n"); scanf ("%d",&m); switch (m) { case 1: { int data; printf ("Please input the element you want to find\n"); scanf ("%d",&data); find(data,&n); }break; case 2: { int i,h; printf ("Please input the element and position you want to insert\n"); scanf ("%d %d",&h,&i); Insert(h,i,&n); printf ("Insert element is %d\n",h); Printf_List(&n); }break; case 3: { int a; printf ("Please input position of the element you want to delete\n "); scanf ("%d",&a); Delete(a,&n); printf ("The element was deleted is %d\n",n.data[a]); Printf_List(&n); }break; } } return 0; }
相关文章推荐
- LeetCode Bitwise AND of Numbers Range
- Error--->android工程导入找不到R文件
- 风风雨雨,我们又一年
- 风风雨雨,我们又一年
- 带你从零学习linux下的socket编程
- mysql的基本使用
- HDU 1235 统计同成绩学生人数(水~)
- Java I/O解读与使用实例
- dop object 中的属性运用
- HDU 1181 变形课(dfs)
- HDU 1170 Balloon Comes!(水~)
- jdk1.5新特性之-----枚举
- HDU 1201 18岁生日(水~)
- HDU 1231 最大连续子序列(最大连续子段和)
- Android中AsyncTask的内存泄露
- python+opencv2生成随机字母
- HDU 1166 敌兵布阵(BIT)
- POJ 1384 && HDU 1114 Piggy-Bank(完全背包问题)
- HDU 1108 最小公倍数(水~)
- HDU 1106 排序(水~)