Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.2 kB
11
Indexable
Never
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int x) : data(x), next(nullptr) {}
};

Node* createLLfromArray(vector<int>& arr) {
    if (arr.size() == 0) {
        return nullptr;
    }

    Node* dumdum = new Node(-1);
    Node* temp = new Node(arr[0]);
    dumdum->next = temp;
    for (int i = 1; i < arr.size(); i++) {
        temp->next = new Node(arr[i]);
        temp = temp->next;
    }
    return dumdum->next;
}

void Alternatify(Node* head) {
    if (head == nullptr) return;

    Node* temp = head->next;
    int a, b, c;
    a = head->data;
    b = temp->data;

    while (temp != nullptr && temp->next != nullptr) {
        temp = temp->next;
        c = temp->data;
        temp->data = a + c;
        a = b;
        b = c;
    }
}

void display(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}

int main() {
    vector<int> arr = {1,2,3,4,5,6,7,8};
    Node* head = createLLfromArray(arr);
    Alternatify(head);
    display(head);
    return 0;
}