C语言链表创建与显示示例代码
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createList(int n);
void displayList(struct Node* head);
int main() {
int n;
struct Node* head;
printf("Enter the number of nodes: ");
scanf("%d", &n);
head = createList(n);
printf("\nDisplaying the list:\n");
displayList(head);
return 0;
}
struct Node* createList(int n) {
int i, data;
struct Node *head, *newNode, *temp;
head = NULL;
if (n == 0) {
return NULL;
}
printf("Enter the data of node 1: ");
scanf("%d", &data);
head = (struct Node*)malloc(sizeof(struct Node));
head->data = data;
head->next = NULL;
temp = head;
for (i = 2; i <= n; i++) {
newNode = (struct Node*)malloc(sizeof(struct Node));
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
return head;
}
void displayList(struct Node* head) {
struct Node* temp = head;
int count = 0;
while (temp != NULL) {
printf("Data %d = %d\n", ++count, temp->data);
temp = temp->next;
}
printf("Total number of nodes = %d\n", count);
}
原文地址: https://www.cveoy.top/t/topic/nraS 著作权归作者所有。请勿转载和采集!