用c语言写一段完整的求单链表中节点个数的代码。要求有输入与输出
#include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node* next; } Node;
int countNodes(Node* head) { int count = 0; Node* current = head; while (current != NULL) { count++; current = current->next; } return count; }
void insert(Node** head, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList(Node* head) { Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); }
int main() { Node* head = NULL; int n, data; printf("Enter the number of nodes: "); scanf("%d", &n); printf("Enter the data values:\n"); for (int i = 0; i < n; i++) { scanf("%d", &data); insert(&head, data); } printf("The linked list is: "); printList(head); int count = countNodes(head); printf("The number of nodes in the linked list is: %d\n", count); return 0;
原文地址: https://www.cveoy.top/t/topic/fbkT 著作权归作者所有。请勿转载和采集!