建立一个单向链表,要求从键盘输入元素的值,并,实现元素插入删除按键查找的功能
时间: 2024-02-13 18:06:47 浏览: 79
好的,我可以帮你实现这个功能。首先,定义一个节点结构体,包含数据和指向下一个节点的指针:
```c
typedef struct node {
int data;
struct node* next;
} Node;
```
然后,定义一个全局的头指针和尾指针:
```c
Node* head = NULL;
Node* tail = NULL;
```
接下来,实现插入元素的函数。这里提供两种插入方法:在链表尾部插入和在链表任意位置插入。在尾部插入的函数如下:
```c
void insertAtTail(int data) {
Node* newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (tail == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
```
在任意位置插入的函数如下:
```c
void insertAtIndex(int index, int data) {
Node* newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (index == 0) {
newNode->next = head;
head = newNode;
if (tail == NULL) {
tail = head;
}
} else {
Node* current = head;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
if (newNode->next == NULL) {
tail = newNode;
}
}
}
```
接下来,实现删除元素的函数。同样提供两种删除方法:删除链表头部元素和删除任意位置元素。删除头部元素的函数如下:
```c
void deleteAtHead() {
if (head == NULL) {
return;
}
Node* temp = head;
head = head->next;
free(temp);
if (head == NULL) {
tail = NULL;
}
}
```
删除任意位置元素的函数如下:
```c
void deleteAtIndex(int index) {
if (index == 0) {
deleteAtHead();
return;
}
Node* current = head;
Node* prev = NULL;
for (int i = 0; i < index; i++) {
if (current == NULL) {
return;
}
prev = current;
current = current->next;
}
prev->next = current->next;
free(current);
if (prev->next == NULL) {
tail = prev;
}
}
```
最后,实现按键查找元素的函数:
```c
Node* search(int data) {
Node* current = head;
while (current != NULL) {
if (current->data == data) {
return current;
}
current = current->next;
}
return NULL;
}
```
这样,一个简单的单向链表就实现了,你可以在主函数中通过调用这些函数来实现你的需求。
阅读全文