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

ผลรวมโหนดของ Singly Linked List ในภาษา C

Singly Linked List เป็นโครงสร้างข้อมูลที่แต่ละโหนดมีค่า (data) และตัวชี้ไปยังโหนดถัดไป (next) เพื่อหาผลรวมค่าทุกโหนด ให้เดินทางผ่านลิสต์และสะสมค่า

ตัวอย่าง

Linked List: 2 → 27 → 32 → 1 → 5

Sum = 2 + 27 + 32 + 1 + 5 = 67

วิธีที่ 1: ใช้ลูป (Iterative)

#include <iostream>
using namespace std;

struct Node {
    int data;
    struct Node* next;
};

void push(struct Node** headRef, int val) {
    struct Node* newNode = new Node;
    newNode->data = val;
    newNode->next = *headRef;
    *headRef = newNode;
}

int main() {
    struct Node* head = NULL;
    int sum = 0;
    push(&head, 95);
    push(&head, 60);
    push(&head, 87);
    push(&head, 6);
    push(&head, 12);
    
    struct Node* ptr = head;
    while (ptr != NULL) {
        sum += ptr->data;
        ptr = ptr->next;
    }
    cout << "Sum of nodes = " << sum;
    return 0;
}

วิธีที่ 2: ใช้ Recursive

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    struct Node* next;
};

void push(struct Node** headRef, int newData) {
    struct Node* newNode = new Node;
    newNode->data = newData;
    newNode->next = *headRef;
    *headRef = newNode;
}

void nodeSum(struct Node* head, int* sum) {
    if (!head) return;
    nodeSum(head->next, sum);
    *sum = *sum + head->data;
}

int main() {
    struct Node* head = NULL;
    int sum = 0;
    push(&head, 95);
    push(&head, 60);
    push(&head, 87);
    push(&head, 6);
    push(&head, 12);
    nodeSum(head, &sum);
    cout << "Sum of nodes = " << sum;
    return 0;
}

ผลลัพธ์ (ทั้งสองวิธี)

Sum of nodes = 260