顺序表的基本操作
/**顺序表的建立,插入,删除,及遍历*/
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<cctype> #include<queue> #include<vector> #include<algorithm> #define N 1001000 #define INf 0X3f3f3f3f using namespace std; typedef long long LL; #define MAXSIZE 100 #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType elem[MAXSIZE]; int length; }SqList; Status InitList_Sq(SqList &L)//建立 { L.length=0; return OK; } Status ListInsert_Sq(SqList &L, int i, ElemType x)//插入 { int j; SqList p; if(i<1 || i>L.length+1) return ERROR; if(L.length==MAXSIZE-1) return OVERFLOW; for(j=L.length; j>=i; j--) L.elem[j]=L.elem[j-1]; L.elem[i-1]=x; L.length++; printf("\n请实现顺序表的插入运算!\n"); return OK; } Status ListDelete_Sq(SqList &L, int i, ElemType &e)//删除 { int j; if(i<1 || i>L.length) return ERROR; e=L.elem[i-1]; for(j=i; j<L.length; j++) L.elem[j-1]=L.elem[j]; L.length--; printf("\n请实现顺序表的删除运算!\n"); return OK; } void TravelseList_Sq(SqList L)//遍历 { int i; for(i=0; i<L.length; i++) printf("%d\t", L.elem[i]); printf("\n"); } int main() { int i, n; ElemType x; SqList L1; InitList_Sq(L1); printf("请输入元素的个数:"); scanf("%d", &n); printf("请输入%d个数:", n); for(i=0; i<n; i++) scanf("%d", &(L1.elem[i])); L1.length=n; printf("\n请输入插入的位置\n"); scanf("%d", &i); printf("\n请输入插入元素的值\n"); scanf("%d", &x); if(ListInsert_Sq(L1, i, x)==1) { printf("插入成功!插入后顺序表中元素为:\n\n"); TravelseList_Sq(L1);//显示所有元素 } else printf("插入失败!\n"); printf("\n请输入删除位置:"); scanf("%d", &i); if(ListDelete_Sq(L1, i, x)) { printf("\n删除了元素%d,删除后顺序表中元素为:\n", x); TravelseList_Sq(L1); } else printf("删除失败!\n"); return 0; }