1、根据给定的整型数组,以尾插法建立一个单链表,并实现以下操作: ① 查找:输入一个欲查找的整数,找到则显示第一个相匹配的整数在单链表中所处的位置,若不存在,则显示提示信息。 ② 删除:输入一个欲删除的整数e ,若存在则在单链表中删除第一个值为e 的元素。 ③ 插入:输入一个欲插入位置i 和欲插入元素e,将e 插入到第i 个整数之前(注意i 的合法性)。
时间: 2023-05-11 15:05:11 浏览: 45
好的,根据您的要求,我将扮演一个由 CSDN 开发的C知道,是一个类 ChatGPT 的 AI。关于您的问题,我可以回答:
以下是根据给定的整型数组,以尾插法建立单链表的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int arr[], int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int find(Node *head, int x) {
int pos = 1;
while (head != NULL) {
if (head->data == x) {
return pos;
}
head = head->next;
pos++;
}
printf("Not found.\n");
return -1;
}
void delete(Node **head, int x) {
Node *prev = NULL, *curr = *head;
while (curr != NULL) {
if (curr->data == x) {
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
printf("Not found.\n");
}
void insert(Node **head, int pos, int x) {
if (pos < 1) {
printf("Invalid position.\n");
return;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
if (pos == 1) {
newNode->next = *head;
*head = newNode;
} else {
Node *prev = NULL, *curr = *head;
int i = 1;
while (curr != NULL && i < pos) {
prev = curr;
curr = curr->next;
i++;
}
if (curr == NULL && i < pos) {
printf("Invalid position.\n");
free(newNode);
return;
}
newNode->next = curr;
prev->next = newNode;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
Node *head = createList(arr, n);
printList(head);
printf("%d\n", find(head, 3));
delete(&head, 3);
printList(head);
insert(&head, 3, 3);
printList(head);
return 0;
}
```
这段代码实现了尾插法建立单链表,并且提供了查找、删除和插入操作。
如果您有其它问题,欢迎继续提问。