fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MaxSize 100
  4. typedef int ElemType;
  5. typedef struct {
  6. ElemType data[MaxSize]; /* 存放数据元素 */
  7. int length; /* 线性表长度 */
  8. } SqList;
  9.  
  10. /* 初始化 */
  11. void InitList(SqList *L) { L->length = 0; }
  12.  
  13. /* 在位置i(1≤i≤n+1)插入元素e */
  14. int ListInsert(SqList *L, int i, ElemType e) {
  15. int j;
  16. if (i < 1 || i > L->length + 1 || L->length >= MaxSize) return 0;
  17. for (j = L->length; j >= i; j--) L->data[j] = L->data[j-1];
  18. L->data[i-1] = e; L->length++; return 1;
  19. }
  20.  
  21. /* 删除位置i的元素并由e返回 */
  22. int ListDelete(SqList *L, int i, ElemType *e) {
  23. int j;
  24. if (i < 1 || i > L->length) return 0;
  25. *e = L->data[i-1];
  26. for (j = i; j < L->length; j++) L->data[j-1] = L->data[j];
  27. L->length--; return 1;
  28. }
  29.  
  30. /* 按位取值 */
  31. int GetElem(SqList L, int i, ElemType *e) {
  32. if (i < 1 || i > L.length) return 0;
  33. *e = L.data[i-1]; return 1;
  34. }
  35.  
  36. /* 按值查找,返回其逻辑位置 */
  37. int LocateElem(SqList L, ElemType e) {
  38. int i;
  39. for (i = 0; i < L.length; i++)
  40. if (L.data[i] == e) return i + 1;
  41. return 0;
  42. }
  43.  
  44. /* 遍历输出 */
  45. void DispList(SqList L) {
  46. int i;
  47. for (i = 0; i < L.length; i++) printf("%d ", L.data[i]);
  48. printf("\n");
  49. }
  50.  
  51. int main() {
  52. SqList L; ElemType e;
  53. int a[] = {1, 2, 3, 4, 5}, i;
  54. InitList(&L);
  55. for (i = 0; i < 5; i++) ListInsert(&L, i+1, a[i]);
  56. printf("初始顺序表: "); DispList(L);
  57. ListInsert(&L, 3, 100);
  58. printf("在位置3插入100后: "); DispList(L);
  59. ListDelete(&L, 3, &e);
  60. printf("删除第3个元素(%d)后: ", e); DispList(L);
  61. GetElem(L, 2, &e); printf("第2个元素=%d\n", e);
  62. printf("元素3的位置=%d\n", LocateElem(L, 3));
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 5352KB
stdin
Standard input is empty
stdout
初始顺序表:  1 2 3 4 5 
在位置3插入100后: 1 2 100 3 4 5 
删除第3个元素(100)后: 1 2 3 4 5 
第2个元素=2
元素3的位置=3