建立单链表存储数据(10,20,30,40,50,60,70,80,90,100),要求: (1)头插法或尾插法建立单链表,并输出单链表中所有元素; (2)输出单链表中的最大值和最小值; (3)键盘输入一个值x,输出链表中第一个值为x的元素的位序; (4)键盘输入一位序值b,在第b个元素之前插入值为500的元素,输出链表中的所有数据; (5)键盘输入位序值m,删除位序为m的元素,输出链表中的所有数据; (6)输出单链表的长度。c语言实现
时间: 2024-03-03 20:52:06 浏览: 157
以下是C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// 头插法建立单链表
struct Node* createListHead(int arr[], int n) {
struct Node* head = NULL;
for (int i = 0; i < n; i++) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = head;
head = node;
}
return head;
}
// 尾插法建立单链表
struct Node* createListTail(int arr[], int n) {
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < n; i++) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = NULL;
if (tail == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 输出单链表中所有元素
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 输出单链表中的最大值和最小值
void printMaxMin(struct Node* head) {
int max = head->data;
int min = head->data;
while (head != NULL) {
if (head->data > max) {
max = head->data;
}
if (head->data < min) {
min = head->data;
}
head = head->next;
}
printf("最大值:%d,最小值:%d\n", max, min);
}
// 输出链表中第一个值为x的元素的位序
void printXPos(struct Node* head, int x) {
int pos = 1;
while (head != NULL) {
if (head->data == x) {
printf("第一个值为%d的元素的位序:%d\n", x, pos);
return;
}
head = head->next;
pos++;
}
printf("链表中没有值为%d的元素\n", x);
}
// 在第b个元素之前插入值为500的元素,并输出链表中的所有数据
void insertBeforeB(struct Node* head, int b) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = 500;
int pos = 1;
while (head != NULL) {
if (pos == b - 1) {
node->next = head->next;
head->next = node;
break;
}
head = head->next;
pos++;
}
printList(head);
}
// 删除位序为m的元素,并输出链表中的所有数据
void deletePosM(struct Node* head, int m) {
if (m == 1) {
head = head->next;
printList(head);
return;
}
int pos = 1;
while (head != NULL) {
if (pos == m - 1) {
head->next = head->next->next;
break;
}
head = head->next;
pos++;
}
printList(head);
}
// 输出单链表的长度
int getLength(struct Node* head) {
int length = 0;
while (head != NULL) {
length++;
head = head->next;
}
return length;
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int n = sizeof(arr) / sizeof(arr[0]);
struct Node* head = createListHead(arr, n);
printList(head);
printMaxMin(head);
printXPos(head, 30);
insertBeforeB(head, 3);
deletePosM(head, 5);
printf("链表长度:%d\n", getLength(head));
return 0;
}
```
阅读全文