โจทย์
กำหนด Linked List ให้คำนวณผลคูณของโหนดสลับ (โหนดที่ 1, 3, 5, ...) โดยไม่เปลี่ยนตำแหน่งโหนด
ตัวอย่าง
Input: 10 → 20 → 30 → 40 → 50 → 60 Output: 15000 (10 × 30 × 50)
วิธีการ
- สร้าง pointer temp ชี้ที่โหนดแรก
- กำหนด product = head->data (โหนดแรก)
- วนลูป while (temp->next != NULL && temp != NULL && temp->next->next != NULL): temp = temp->next->next, product = product * temp->data
- แสดงผล product
อัลกอริทึม
- สร้างโครงสร้างโหนด struct node {int data; struct node *next;}
- ฟังก์ชัน insert() เพิ่มโหนดท้ายลิสต์
- ฟังก์ชัน display() แสดงลิสต์
- ฟังก์ชัน alternate() คำนวณผลคูณโหนดสลับ: เริ่มจาก head->data แล้วกระโดด temp->next->next
- ใน main(): สร้างลิสต์ 10-60 เรียก display() และ alternate()
โค้ดภาษา 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;
if (head == NULL) {
head = newnode;
head->next = NULL;
} else {
temp = head;
while (temp->next != NULL)
temp = temp->next;
newnode->next = NULL;
temp->next = newnode;
}
}
void display() {
if (head == NULL)
printf("no node ");
else {
temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
}
void alternate() {
int product;
temp = head;
product = head->data;
while (temp->next != NULL && temp != NULL && temp->next->next != NULL) {
temp = temp->next->next;
product = product * (temp->data);
}
printf("\nproduct of alternate nodes is %d : ", product);
}
int main() {
struct node* head = NULL;
insert(10);
insert(20);
insert(30);
insert(40);
insert(50);
insert(60);
printf("linked list is : ");
display();
alternate();
return 0;
}ผลลัพธ์
linked list is : 10 20 30 40 50 60 product of alternate nodes is : 15000