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(' '); }
int main() { Node* head = NULL; int n, data; printf("Enter the number of nodes: "); scanf("%d", &n); printf("Enter the data values: "); 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/n32v 著作权归作者所有。请勿转载和采集!