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 xen kẽ của danh sách liên kết trong C

Bài toán

Cho danh sách liên kết, tính tích các nút xen kẽ (bỏ qua một nút, lấy một nút) bắt đầu từ nút đầu.

Ví dụ

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

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

Phương pháp

  • Con trỏ temp trỏ đến head
  • product = head->data (lấy nút đầu)
  • Duyệt: temp = temp->next->next (nhảy 2 nút)
  • Điều kiện dừng: temp->next != NULL && temp != NULL && temp->next->next != NULL
  • Nhân tích lũy: product *= temp->data

Thuật toán

Bắt đầu
Bước 1: Struct node, con trỏ head, temp
Bước 2: Hàm insert(val)
Bước 3: Hàm display()
Bước 4: Hàm alternate()
    product = head->data
    temp = head
    While (temp->next && temp && temp->next->next):
        temp = temp->next->next
        product *= temp->data
    In product
Bước 5: main(): tạo danh sách 10,20,30,40,50,60 → gọi alternate()
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;
    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("Danh sách rỗng");
    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 *= temp->data;
    }
    printf("\nTích các nút xen kẽ: %d", product);
}

int main() {
    head = NULL;
    insert(10); insert(20); insert(30);
    insert(40); insert(50); insert(60);
    printf("Danh sách: ");
    display();
    alternate();
    return 0;
}

Kết quả

Danh sách: 10 20 30 40 50 60
Tích các nút xen kẽ: 15000