首页 > 代码库 > 嵌入式菜鸟算法②---顺序表操作
嵌入式菜鸟算法②---顺序表操作
主要内容:顺序表插入、删除
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 1024 typedef int datatype; typedef struct { datatype data[MAXSIZE]; int last; // subscript of linear list's last node,i.e. length is n = last + 1 }sequenlist; /* linear list insert operate */ int Insert(sequenlist* L, datatype x, int i) { int j; if (L->last >= MAXSIZE - 1) { printf("space overflow!\n"); return 0; } else if (i < 1 || (i > L->last + 2)) { printf("insert in a invalide position!\n"); return 0; } else { for (j = L->last; j >= i-1; j--) { L->data[j+1] = L->data[j]; // give space for insert new data } L->data[i-1] = x; L->last = L->last+1; } return 1; } /* linear list delete operate */ int Delete(sequenlist* L, int i) { int j; if (i < 1 || (i > L->last + 1)) { printf("delete position is invalide!\n"); return 0; } else { for (j = i; j <= L->last; j++) { L->data[j-1] = L->data[j]; } L->last = L->last-1; } return 1; } int main() { sequenlist *L; int i, ch, n; while(1) // shouw the menu { printf("\n*****Please select:"); printf("\n(1) input sequenlist"); printf("\n(2) insert sequenlist"); printf("\n(3) delete sequenlist"); printf("\n*****End*************"); ch = getch(); // get keyboard input switch(ch) { case '1': printf("\nPlease input your sequenlist's number n = "); scanf("%d", &n); L = (sequenlist*)malloc(sizeof(sequenlist)); for (i = 0; i < n; i++) { printf("\n Please input %dth interger:", i+1); scanf("%d", &L->data[i]); } L->last = n-1; printf("your input sequenlist is:\n"); for (i = 0; i<=L->last; i++) { printf("%d\n", L->data[i]); } break; case '2': printf("\n Please input the value to insert:"); scanf("%d", &n); printf("\nPlease input the position to insert"); scanf("%d", &i); printf("\n"); if (Insert(L, n, i)) { printf("the insert result is:\n"); for (i = 0; i <= L->last; i++) { printf("%d", L->data[i]) ; printf("\n"); } } break; case '3': printf("\n Please input the delete data's position:"); scanf("%d", &i); printf("\n"); if (Delete(L, i)) { printf("the delete result is:\n"); for (i = 0; i<=L->last; i++) { printf("%d\n", L->data[i]); } } break; case '4': return; default: return; } } return 0; }
输出结果:
嵌入式菜鸟算法②---顺序表操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。