本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中所有存储了某给定值的结点删除。链表结点定义如下:\n\nstruct listnode {\n int data;\n listnode
时间: 2023-06-05 18:48:11 浏览: 99
链表的建立与结点的删除
{
struct listnode* next;
};
// 将读入的数据存储为单链表
struct listnode* createList(int* arr, int size) {
struct listnode* head = NULL;
struct listnode* tail = NULL;
for (int i = ; i < size; i++) {
struct listnode* node = (struct listnode*)malloc(sizeof(struct listnode));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 将链表中所有存储了某给定值的结点删除
struct listnode* deleteNode(struct listnode* head, int value) {
struct listnode* prev = NULL;
struct listnode* curr = head;
while (curr != NULL) {
if (curr->data == value) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
struct listnode* temp = curr;
curr = curr->next;
free(temp);
} else {
prev = curr;
curr = curr->next;
}
}
return head;
}
阅读全文