用c语言写一个代码,满足以下条件:1. 创建空单链表; 2. 在单链表上通过插入A~E建立非空单链表并输出; 3. 取第3个数据元素并输出; 4. 在已有单链表里查找B,并输出查找结果; 5. 删除单链表里的第4个数据元素并输出删除后的单链表。
时间: 2024-10-08 14:04:15 浏览: 29
C语言实现头插法、尾插法两种方法来构建带头结点的单链表.zip
首先,我们需要创建一个链表节点的数据结构,然后分别实现创建链表、插入节点、查找元素、删除元素和输出链表的功能。以下是满足上述条件的一个简单C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node* next;
} Node;
Node* createEmptyList() {
Node* head = NULL;
return head;
}
void insertNode(Node** head, char data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void displayList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%c -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
char findElement(Node* head, char target) {
Node* temp = head;
while (temp != NULL) {
if (temp->data == target) {
return temp->data;
}
temp = temp->next;
}
return '\0'; // 如果未找到,返回'\0'
}
Node* deleteElement(Node** head, int index) {
if (*head == NULL) return NULL;
if (index == 0) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return *head;
}
Node* current = *head;
for (int i = 1; i < index && current != NULL; ++i) {
current = current->next;
}
if (current == NULL || current->next == NULL) {
printf("Invalid index!\n");
return *head;
}
Node* toDelete = current->next;
current->next = current->next->next;
free(toDelete);
return *head;
}
int main() {
Node* list = createEmptyList();
insertNode(&list, 'A');
insertNode(&list, 'B');
insertNode(&list, 'C');
insertNode(&list, 'D');
insertNode(&list, 'E');
displayList(list);
printf("The third element is: %c\n", list->next->data); // 输出C
char found = findElement(list, 'B');
if (found != '\0') {
printf("Found B: %c\n", found);
} else {
printf("Not found B in the list.\n");
}
list = deleteElement(&list, 3); // 删除第四个元素'D'
displayList(list);
return 0;
}
```
注意:这个代码会在删除第4个元素时显示整个列表,因为链表是从头开始计数的,所以第4个元素的实际位置是索引3。此外,如果提供的索引超出范围,程序会打印错误消息。
阅读全文