写一个C++程序:定义一个双向链表,并给出其增删改查的函数
时间: 2024-05-27 07:13:02 浏览: 145
好的,以下是所需的C语言程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
typedef struct List {
Node* head;
Node* tail;
int size;
} List;
void init(List* list) {
list->head = NULL;
list->tail = NULL;
list->size = 0;
}
void add(List* list, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->prev = list->tail;
node->next = NULL;
if (list->tail != NULL) {
list->tail->next = node;
}
list->tail = node;
if (list->head == NULL) {
list->head = node;
}
list->size++;
}
void remove_last(List* list) {
if (list->size > 0) {
Node* node = list->tail;
if (list->tail == list->head) {
list->tail = NULL;
list->head = NULL;
} else {
list->tail = node->prev;
node->prev->next = NULL;
}
free(node);
list->size--;
}
}
void update(List* list, int index, int data) {
if (index < list->size) {
Node* node = list->head;
for (int i = 0; i < index; i++) {
node = node->next;
}
node->data = data;
}
}
int find(List* list, int data) {
Node* node = list->head;
int index = 0;
while (node != NULL) {
if (node->data == data) {
return index;
}
index++;
node = node->next;
}
return -1;
}
int main() {
List list;
init(&list);
add(&list, 1);
add(&list, 2);
add(&list, 3);
add(&list, 4);
remove_last(&list);
update(&list, 1, 5);
printf("The index of data 3 is %d\n", find(&list, 3));
printf("The index of data 5 is %d\n", find(&list, 5));
return 0;
}
回答完毕。
阅读全文