(1)c语言产生20个1~200的随机整数,并依次保存到带头结点的单链表中。(2)计算单链表的长度,并将结果存放在头结点的数据域中,然后输出单链表的所有元素。(3)从单链表中删除与给定值x相等的所有结点,并输出结果。
时间: 2024-10-14 07:12:54 浏览: 44
链表-使用C语言实现带头结点的单链表.zip
(1)在C语言中生成并插入随机整数到链表的操作可以分为以下几个步骤:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 生成随机数并插入链表
void insertRandom(Node** head, int min, int max) {
srand(time(0)); // 设置随机种子
for (int i = 0; i < 20; ++i) {
int num = rand() % (max - min + 1) + min;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = *head;
*head = newNode;
}
}
// 计算链表长度并更新头节点
void calcAndSetLength(Node* head) {
int length = 0;
Node* current = head;
while (current != NULL) {
length++;
current = current->next;
}
head->data = length;
}
// 输出链表元素
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 删除链表中值为x的节点
void deleteNodes(Node** head, int x) {
Node* prev = NULL, *current = *head;
while (current != NULL && current->data == x) {
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
current = current->next;
}
}
// 示例演示
int main() {
Node* head = NULL;
insertRandom(&head, 1, 200);
calcAndSetLength(head);
printf("链表长度: %d\n", head->data);
printList(head);
int valueToDelete = 50;
deleteNodes(&head, valueToDelete);
printList(head);
return 0;
}
```
阅读全文