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

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

โจทย์

กำหนด Linked List ให้คำนวณผลคูณของโหนดสลับ (โหนดที่ 1, 3, 5, ...) โดยไม่เปลี่ยนตำแหน่งโหนด

ตัวอย่าง

Input: 10 → 20 → 30 → 40 → 50 → 60
Output: 15000 (10 × 30 × 50)

วิธีการ

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

อัลกอริทึม

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