用C语言:(1)实现单链表的创建;(2)实现单链表的插入;(3)实现单链表的删除(4)实现单链表的查找;(5)实现单链表的显示;
时间: 2023-05-11 22:04:43 浏览: 94
1. 实现单链表的创建:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createLinkedList(int n) {
struct Node *head, *p, *q;
int i, data;
head = (struct Node*)malloc(sizeof(struct Node));
if (head == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
printf("Enter the data for node %d: ", i+1);
scanf("%d", &data);
p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
p->data = data;
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
```
2. 实现单链表的插入:
```c
void insertNode(struct Node* head, int position, int data) {
struct Node* p, *q;
int i;
p = head;
for (i = 0; i < position-1; i++) {
if (p == NULL) {
printf("Invalid position.\n");
return;
}
p = p->next;
}
q = (struct Node*)malloc(sizeof(struct Node));
if (q == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
q->data = data;
q->next = p->next;
p->next = q;
}
```
3. 实现单链表的删除:
```c
void deleteNode(struct Node* head, int position) {
struct Node* p, *q;
int i;
p = head;
for (i = 0; i < position-1; i++) {
if (p == NULL) {
printf("Invalid position.\n");
return;
}
p = p->next;
}
q = p->next;
p->next = q->next;
free(q);
}
```
4. 实现单链表的查找:
```c
int searchNode(struct Node* head, int data) {
struct Node* p;
int position = 0;
p = head->next;
while (p != NULL) {
position++;
if (p->data == data) {
return position;
}
p = p->next;
}
return -1;
}
```
5. 实现单链表的显示:
```c
void displayLinkedList(struct Node* head) {
struct Node* p;
p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
以上是用 C 语言实现单链表的创建、插入、删除、查找和显示的代码。
阅读全文