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

Differentiate between Unimodal, Bimodal and Multimodal with graphic representation.

Using Titanic dataset, do the following: a. Find total number of passengers with age less than 30 b. Find total fare paid by passengers of first class c. Compare number of survivors of each passenger class

Import iris data using sklearn library . Compute mean, mode, median, standard deviation, confidence interval and standard error for each feature ii. Compute correlation coefficients between each pair of features and plot heatmap iii. Find covariance between length of sepal and petal iv. Build contingency table for class feature