C语言实现顺序表的基本操作
C语言实现顺序表的基本操作
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define MAX_SIZE 100 5 6 typedef struct { 7 int data[MAX_SIZE]; 8 int length; 9 } SeqList; 10 11 void initList(SeqList* list) { 12 list->length = 0; 13 } 14 15 void insert(SeqList* list, int position, int item) { 16 int i; // 将变量的声明移至此处 17 18 if (position < 0 || position > list->length || list->length == MAX_SIZE) { 19 printf("Invalid position or list is full\n"); 20 return; 21 } 22 23 for (i = list->length - 1; i >= position; i--) { 24 list->data[i + 1] = list->data[i]; 25 } 26 27 list->data[position] = item; 28 list->length++; 29 } 30 31 void delete(SeqList* list, int position) { 32 int i; // 将变量的声明移至此处 33 34 if (position < 0 || position >= list->length) { 35 printf("Invalid position\n"); 36 return; 37 } 38 39 for (i = position; i < list->length - 1; i++) { 40 list->data[i] = list->data[i + 1]; 41 } 42 43 list->length--; 44 } 45 46 int search(SeqList* list, int key) { 47 int i; // 将变量的声明移至此处 48 49 for (i = 0; i < list->length; i++) { 50 if (list->data[i] == key) { 51 return i; 52 } 53 } 54 55 return -1; 56 } 57 58 void display(SeqList* list) { 59 int i; // 将变量的声明移至此处 60 61 printf("List elements: "); 62 for (i = 0; i < list->length; i++) { 63 printf("%d ", list->data[i]); 64 } 65 printf("\n"); 66 } 67 68 int main() { 69 SeqList list; 70 int choice, item, position, key, index; 71 72 initList(&list); 73 74 while (1) { 75 printf("1. Insert\n"); 76 printf("2. Delete\n"); 77 printf("3. Search\n"); 78 printf("4. Display\n"); 79 printf("5. Exit\n"); 80 81 printf("Enter your choice: "); 82 scanf("%d", &choice); 83 84 switch (choice) { 85 case 1: 86 printf("Enter the element to be inserted: "); 87 scanf("%d", &item); 88 printf("Enter the position: "); 89 scanf("%d", &position); 90 insert(&list, position, item); 91 break; 92 case 2: 93 printf("Enter the position: "); 94 scanf("%d", &position); 95 delete(&list, position); 96 break; 97 case 3: 98 printf("Enter the key to search: "); 99 scanf("%d", &key); 100 index = search(&list, key); 101 if (index != -1) { 102 printf("Element found at position: %d\n", index); 103 } else { 104 printf("Element not found\n"); 105 } 106 break; 107 case 4: 108 display(&list); 109 break; 110 case 5: 111 exit(0); 112 default: 113 printf("Invalid choice\n"); 114 break; 115 } 116 } 117 118 return 0; 119 }
浙公网安备 33010602011771号