Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Tính tích các nút của danh sách liên kết đơn trong C

Bài toán

Cho danh sách liên kết đơn, tính tích của tất cả các nút. Duyệt từ nút đầu đến khi gặp NULL.

Ví dụ

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

Tính tích các nút của danh sách liên kết đơn trong C

Phương pháp

  • Con trỏ temp trỏ đến head
  • Duyệt khi temp != NULL
  • product = product * (temp->data)
  • temp = temp->next

Thuật toán

Bắt đầu
Bước 1: Định nghĩa struct node, con trỏ head, temp
Bước 2: Hàm insert(val) - chèn nút
Bước 3: Hàm display() - hiển thị
Bước 4: Hàm product_nodes()
    product = 1
    temp = head
    While temp != NULL:
        product *= temp->data
        temp = temp->next
    In product
Bước 5: main(): tạo danh sách 1..6, gọi display và product_nodes
Kết thúc

Mã nguồn 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("Danh sách rỗng");
    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 *= temp->data;
        temp = temp->next;
    }
    printf("\nTích các nút: %d", product);
}

int main() {
    head = NULL;
    insert(1); insert(2); insert(3);
    insert(4); insert(5); insert(6);
    printf("Danh sách: ");
    display();
    product_nodes();
    return 0;
}

Kết quả

Danh sách: 1 2 3 4 5 6
Tích các nút: 720