ปัญหา: นับจำนวนโหนด (Nodes) ใน Singly Linked List ด้วย Recursion
โครงสร้างโหนด: struct node { int data; struct node *next; }
ฟังก์ชัน Recursive หาความยาว
int length(node *temp) {
if (temp == NULL)
return l;
else {
l = l + 1;
length(temp->next);
}
}
ตัวแปร global int l = 0; ใช้สะสมจำนวน
โค้ด C เต็ม (พร้อมเมนูเพิ่ม/แสดง)
#include <stdio.h>
#include <stdlib.h>
typedef struct linklist {
int data;
struct linklist *next;
} node;
int l = 0;
int main() {
node *head = NULL, *temp, *temp1;
int len, choice, count = 0, key;
do {
temp = (node *)malloc(sizeof(node));
if (temp != NULL) {
printf("\nenter the elements in a list : ");
scanf("%d", &temp->data);
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
temp1 = head;
while (temp1->next != NULL) {
temp1 = temp1->next;
}
temp1->next = temp;
}
} else {
printf("\nMemory is full");
}
printf("\npress 1 to enter data into list: ");
scanf("%d", &choice);
} while (choice == 1);
len = length(head);
printf("The list has %d no of nodes", l);
return 0;
}
int length(node *temp) {
if (temp == NULL)
return l;
else {
l = l + 1;
length(temp->next);
}
}
ตัวอย่าง Output
Run 1:
enter the elements in a list: 3
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 0
The list has 3 no of nodes