Inserting in and appending to a single linked list

Single Linked List : Insert and Append Operations

Time Complexity : O(N). N is the number of nodes inserted into or appended to the linked list.
Space Complexity : O(N). N is the number of nodes inserted into or appended to the linked list.


C++ : Single linked list, insert & append operations. Implemented in C++11

#include<iostream>

using namespace std;

class Node {

    public:
    int data;
    Node* next;
    Node(int arg_data) : data(arg_data), next(NULL)
    {}
};

class SingleLinkedList {

    public:

    SingleLinkedList()
    {}

    // Insert a new node into the single linked list after the first found node.
    void Insert(Node* head, int after, int data) {

        Node*  current = head;

        while (current != NULL and current->data != after) {
            current = current->next;
        }

        if (current != NULL) {
            Node * new_node = new Node(data);
            Node * next_node = current->next;
            current->next = new_node;
            new_node->next = next_node;
        }
    }

    // Append a node the the linked list
    void Append(Node* head, int data) {

        Node* current = head;
        while (current->next != NULL) {
            current = current->next;
        }
        Node* new_node = new Node(data);
        current->next = new_node;
    }

    void Display(Node* head) {

        Node* current = head;
        while (current != NULL) {
            cout << current->data << " ";
            current = current->next;
        }
    }
};

int main() {

   Node* head = new Node(2);
   head->next = new Node(3);
   head->next->next = new Node(5);
   head->next->next->next = new Node(7);
   head->next->next->next->next = new Node(13);

   SingleLinkedList s;

   int data = 11;
   int after = 7;

   cout << "Before inserting " << data << " after node " << after << endl;
   s.Display(head);
   s.Insert(head, after, data);

   cout << "\nAfter inserting " << data << " after node " << after << endl;
   s.Display(head);

   data = 17;
   cout <<"\nAppending " << data << " to the linked list" << endl;
   s.Append(head, data);

   s.Display(head);

   delete head->next->next->next->next->next->next;
   delete head->next->next->next->next->next;
   delete head->next->next->next->next;
   delete head->next->next->next;
   delete head->next->next;
   delete head->next;
   delete head;

   return 0;
}

Output of insert and append operations on a single linked list. Implemented in C++11

Before inserting 11 after node 7
2 3 5 7 13 
After inserting 11 after node 7
2 3 5 7 11 13 
Appending 17 to the linked list
2 3 5 7 11 13 17

Copyright © 2020, Algotree.org.
All rights reserved.