# 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)
{}
};

public:

{}

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

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) {

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

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

int main() {

int data = 11;
int after = 7;

cout << "Before inserting " << data << " after node " << after << endl;

cout << "\nAfter inserting " << data << " after node " << after << endl;

data = 17;
cout <<"\nAppending " << data << " to the linked list" << endl;

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
``````