111

 avatar
Alexmegawin
c_cpp
2 years ago
2.2 kB
0
Indexable
Never
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
};

class List {
private:
    Node* head;
public:
    List() {
        head = NULL;
    }

    void addNode(int value) {
        Node* newNode = new Node();
        newNode->data = value;
        newNode->next = NULL;

        if (head == NULL) {
            head = newNode;
        }
        else {
            Node* temp = head;
            while (temp->next != NULL) {
                temp = temp->next;
            }
            temp->next = newNode;
        }
    }

    int getNodeValue(int index) {
        if (head == NULL) {
            cout << "List is empty" << endl;
            return -1;
        }

        Node* temp = head;
        int count = 0;
        while (temp != NULL) {
            if (count == index) {
                return temp->data;
            }
            count++;
            temp = temp->next;
        }

        cout << "Index out of range" << endl;
        return -1;
    }

    void deleteNode(int index) {
        if (head == NULL) {
            cout << "List is empty" << endl;
            return;
        }

        Node* temp = head;

        if (index == 0) {
            head = head->next;
            delete temp;
            return;
        }

        int count = 0;
        while (temp != NULL && count < index - 1) {
            temp = temp->next;
            count++;
        }

        if (temp == NULL || temp->next == NULL) {
            cout << "Index out of range" << endl;
            return;
        }

        Node* nextNode = temp->next->next;
        delete temp->next;
        temp->next = nextNode;
    }
};

int main() {
    List list;
    int n, f;
    cin >> n;
    for (int i = 0; i < n; i++) 
    {
        cout << "Enter number ";
        cin >> f;
        list.addNode(f);
    }
    
    /*list.addNode(10);
    list.addNode(15);*/

    cout << "Value at index 1: " << list.getNodeValue(0) << endl;

    list.deleteNode(0);

    cout << "Value at index 1 after deletion: " << list.getNodeValue(0) << endl;

    return 0;
}