统计单链表中偶数位序的元素和并输出元素值。第一行输入链表长度和元素,第二行输出所有偶数元素以及它们的和。c++代码
时间: 2024-05-25 21:19:30 浏览: 30
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createLinkedList(int n);
void printLinkedList(Node* head);
int sumOfEvenNodes(Node* head);
int main() {
int n;
scanf("%d", &n);
Node* head = createLinkedList(n);
printf("The linked list is: ");
printLinkedList(head);
printf("The sum of even nodes is: %d\n", sumOfEvenNodes(head));
return 0;
}
Node* createLinkedList(int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printLinkedList(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int sumOfEvenNodes(Node* head) {
int sum = 0;
Node* curr = head;
int index = 1;
while (curr != NULL) {
if (index % 2 == 0) {
printf("%d ", curr->data);
sum += curr->data;
}
curr = curr->next;
index++;
}
printf("\n");
return sum;
}