#include <stdio.h>
struct Node {
int data;
int next; // 数组的下标 index
};
Node arr[1000] = {0};
int curr = 1;
// malloc
int new_one() {
return curr++;
}
int init() {
int head = new_one();
arr[head].data = 1;
int tail = head;
for (int i = 2; i < 10; ++i) {
int p = new_one();
arr[p].data = i;
arr[p].next = 0;
arr[tail].next = p;
tail = p;
}
return head;
}
void print_list(int head) {
for (int p = head; p != 0; p = arr[p].next) {
printf("%d -> ", arr[p].data);
}
printf("NULL\n");
}
void print_arr(int head) {
for (int i = 0; i < curr; ++i) {
printf("arr[%d] = {data=%d, next=%d}\n", i, arr[i].data, arr[i].next);
}
}
void delete_next(int p) {
arr[p].next = arr[arr[p].next].next;
}
int delete_val(int head, int value) {
for (int p = head; p != 0; p = arr[p].next) {
int next_val = arr[arr[p].next].data;
if (next_val == value) { delete_next(p); }
}
return head;
}
int main() {
int head = init();
printf("init:\n");
print_arr(head);
print_list(head);
delete_val(head, 3);
delete_val(head, 5);
printf("\n");
printf("after delete: \n");
print_list(head);
print_arr(head);
return 0;
}
C语言不用指针,还能写链表吗
于 2023-05-14 22:22:38 首次发布