我正在使用结构实现一个包含 3 个元素的链表。在我介绍计算链表中元素数量的函数之前,它工作正常Linked_list
。以下是 C 语言程序的代码。
C
#include <stdlib.h>
#include <stdio.h>
struct node{
int data;
struct node* next;
};
struct node* Linked_list();
int Length();
int main()
{
int length;
Linked_list();
length = Length();
printf("%d", length);
}
struct node* Linked_list() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("%d %d", head->data, second->data);
}
int Length(struct node* head){
struct node* current = head;
int count = 0;
while(current!=NULL)
{
count++;
current = current->next;
}
return count;
}