Implement singly linked lists.

 Implement singly linked lists.





#include <iostream>


using namespace std;


// Node class represents a single node in the linked list

class Node {

public:

    int data;        // Data stored in the node

    Node* next;    // Pointer to the next node


    // Constructor

    Node(int value) {

        data = value;

        next = nullptr;

    }

};


// Linked list class represents the entire linked list

class LinkedList {

private:

    Node* head;    // Pointer to the head node


public:

    // Constructor

    LinkedList() {

        head = nullptr;

    }


    // Destructor to free memory

    ~LinkedList() {

        Node* current = head;

        while (current != nullptr) {

            Node* next = current->next;

            delete current;

            current = next;

        }

    }


    // Function to insert a node at the beginning of the list

    void insertAtBeginning(int value) {

        Node* newNode = new Node(value);

        newNode->next = head;

        head = newNode;

    }


    // Function to insert a node at the end of the list

    void insertAtEnd(int value) {

        Node* newNode = new Node(value);

        if (head == nullptr) {

            head = newNode;

        } else {

            Node* current = head;

            while (current->next != nullptr) {

                current = current->next;

            }

            current->next = newNode;

        }

    }


    // Function to display the linked list

    void display() {

        Node* current = head;

        while (current != nullptr) {

            cout << current->data << " ";

            current = current->next;

        }

        cout << endl;

    }

};


int main() {

    LinkedList list;


    // Inserting elements at the beginning

    list.insertAtBeginning(3);

    list.insertAtBeginning(2);

    list.insertAtBeginning(1);


    // Displaying the list

    cout << "Linked List after inserting elements at the beginning: ";

    list.display();


    // Inserting elements at the end

    list.insertAtEnd(4);

    list.insertAtEnd(5);

    list.insertAtEnd(6);


    // Displaying the list

    cout << "Linked List after inserting elements at the end: ";

    list.display();


    return 0;

}


Comments

Popular posts from this blog

Load a Pandas dataframe with a selected dataset. Identify and count the missing values in a dataframe. Clean the data after removing noise as follows: a. Drop duplicate rows. b. Detect the outliers and remove the rows having outliers c. Identify the most correlated positively correlated attributes and negatively correlated attributes

The weights of 8 boys in kilograms: 45, 39, 53, 45, 43, 48, 50, 45. Find the median

Download any dataset and do the following: a. Count number of categorical and numeric features b. Remove one correlated attribute (if any) c. Display five-number summary of each attribute and show it visually