โจทย์
กำหนด Singly Linked List ที่มี n โหนด ให้คำนวณผลคูณของข้อมูลในทุกโหนด โดยเดินผ่านลิสต์ตั้งแต่โหนดแรกจนถึง NULL
ตัวอย่าง
Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 720 (1×2×3×4×5×6)
วิธีการ
- สร้าง pointer temp ชี้ที่โหนดแรก (head)
- กำหนด product = 1
- วนลูป while (temp != NULL): product = product * (temp->data), temp = temp->next
- แสดงผล product
อัลกอริทึม
- สร้างโครงสร้างโหนด struct node {int data; struct node *next;}
- ฟังก์ชัน insert() เพิ่มโหนดท้ายลิสต์
- ฟังก์ชัน display() แสดงลิสต์
- ฟังก์ชัน product_nodes() คำนวณผลคูณ: วนลูปคูณ temp->data จน temp == NULL
- ใน main(): สร้างลิสต์ 1-6 เรียก display() และ product_nodes()
โค้ดภาษา C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
} *head, *temp;
void insert(int val) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = val;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
temp = head;
} else {
temp->next = newnode;
temp = temp->next;
}
}
void display() {
if (head == NULL)
printf("no node ");
else {
temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
}
void product_nodes() {
int product = 1;
temp = head;
while (temp != NULL) {
product = product * (temp->data);
temp = temp->next;
}
printf("\nproduct of nodes is : %d", product);
}
int main() {
struct node* head = NULL;
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
insert(6);
printf("linked list is : ");
display();
product_nodes();
return 0;
}ผลลัพธ์
linked list is : 1 2 3 4 5 6 product of nodes is : 720