以C++的方式用递归的方法创建一个带头结点的单链表,遍历输出该单链表,并求出链表中的最大整数,结点个数,所以整数的平均值(double)和删除所以值为给定值x的结点
时间: 2024-05-30 09:14:22 浏览: 36
好的,我了解了你的要求。以下是我对你的第一个问题的回答:
创建带头结点的单链表可以使用递归方法,具体步骤如下:
1.定义一个节点结构体
struct Node {
int data;
struct Node *next;
};
typedef struct Node ListNode;
2.定义一个方法来创建链表
ListNode *CreateList() {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->next = NULL;
ListNode *p = head;
int x;
scanf("%d", &x);
if (x == -1) {
return head;
} else {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = x;
node->next = NULL;
p->next = node;
p = node;
p->next = CreateList();
}
return head;
}
3. 打印链表并求出链表中的最大整数、结点个数和所有整数的平均值如下:
void PrintList(ListNode *head) {
ListNode *p = head->next;
int max_num = p->data;
int count = 1;
double sum = p->data;
while (p) {
printf("%d ", p->data);
if (p->data > max_num) {
max_num = p->data;
}
count++;
sum += p->data;
p = p->next;
}
double average = sum / (count - 1);
printf("\n%d %d %.2f", max_num, count - 1, average);
}
4. 删除值为给定值x的节点方法如下:
void DeleteNode(ListNode *head, int x) {
ListNode *p = head->next;
ListNode *pre = head;
while (p) {
if (p->data == x) {
pre->next = p->next;
free(p);
p = pre->next;
} else {
pre = p;
p = p->next;
}
}
}
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
typedef struct Node ListNode;
ListNode *CreateList() {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->next = NULL;
ListNode *p = head;
int x;
scanf("%d", &x);
if (x == -1) {
return head;
} else {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = x;
node->next = NULL;
p->next = node;
p = node;
p->next = CreateList();
}
return head;
}
void PrintList(ListNode *head) {
ListNode *p = head->next;
int max_num = p->data;
int count = 1;
double sum = p->data;
while (p) {
printf("%d ", p->data);
if (p->data > max_num) {
max_num = p->data;
}
count++;
sum += p->data;
p = p->next;
}
double average = sum / (count - 1);
printf("\n%d %d %.2f", max_num, count - 1, average);
}
void DeleteNode(ListNode *head, int x) {
ListNode *p = head->next;
ListNode *pre = head;
while (p) {
if (p->data == x) {
pre->next = p->next;
free(p);
p = pre->next;
} else {
pre = p;
p = p->next;
}
}
}
int main() {
ListNode *head = CreateList();
PrintList(head);
int x;
scanf("%d", &x);
DeleteNode(head, x);
PrintList(head);
return 0;
}
阅读全文