Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรมคำนวณผลคูณของโหนดทั้งหมดใน Singly Linked List

โจทย์

กำหนด Singly Linked List ที่มี n โหนด ให้คำนวณผลคูณของข้อมูลในทุกโหนด โดยเดินผ่านลิสต์ตั้งแต่โหนดแรกจนถึง NULL

ตัวอย่าง

Input: 1 → 2 → 3 → 4 → 5 → 6
Output: 720 (1×2×3×4×5×6)

วิธีการ

  1. สร้าง pointer temp ชี้ที่โหนดแรก (head)
  2. กำหนด product = 1
  3. วนลูป while (temp != NULL): product = product * (temp->data), temp = temp->next
  4. แสดงผล product

อัลกอริทึม

  1. สร้างโครงสร้างโหนด struct node {int data; struct node *next;}
  2. ฟังก์ชัน insert() เพิ่มโหนดท้ายลิสต์
  3. ฟังก์ชัน display() แสดงลิสต์
  4. ฟังก์ชัน product_nodes() คำนวณผลคูณ: วนลูปคูณ temp->data จน temp == NULL
  5. ใน 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