C语言顺序表实现:插入、删除、获取元素
#include <stdio.h> #include <stdlib.h>
#define MAX_SIZE 100
typedef struct { int data[MAX_SIZE]; int length; } SeqList;
void initList(SeqList *list) { list->length = 0; }
void insertElement(SeqList *list, int element, int position) { if (position < 1 || position > list->length + 1) { printf('Invalid position!\n'); return; }
if (list->length == MAX_SIZE) {
printf('List is full!\n');
return;
}
for (int i = list->length - 1; i >= position - 1; i--) {
list->data[i + 1] = list->data[i];
}
list->data[position - 1] = element;
list->length++;
}
void deleteElement(SeqList *list, int position) { if (position < 1 || position > list->length) { printf('Invalid position!\n'); return; }
for (int i = position; i < list->length; i++) {
list->data[i - 1] = list->data[i];
}
list->length--;
}
int getElement(SeqList *list, int position) { if (position < 1 || position > list->length) { printf('Invalid position!\n'); return -1; }
return list->data[position - 1];
}
int main() { SeqList list; initList(&list);
insertElement(&list, 1, 1);
insertElement(&list, 2, 2);
insertElement(&list, 3, 3);
printf('List: ');
for (int i = 1; i <= list.length; i++) {
printf('%d ', getElement(&list, i));
}
printf('\n');
deleteElement(&list, 2);
printf('List after deletion: ');
for (int i = 1; i <= list.length; i++) {
printf('%d ', getElement(&list, i));
}
printf('\n');
return 0;
}
原文地址: https://www.cveoy.top/t/topic/f3xK 著作权归作者所有。请勿转载和采集!