Insertion Oprations in Linked List
Insertion at the beginning
Click to see the details
To insert the node at the beginning we need to create a new node and assign the head to the new node and the new node to the head.
Code
insertion.cpp
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
void insertAtBeginning(Node* &head, int data) {
Node* newNode = new Node(data);
newNode->next = head;
head = newNode;
}
void printList(Node* head) {
Node* temp = head;
while(temp != nullptr) {
cout << temp->data << "->";
temp = temp->next;
}
cout<<"NULL\n";
}
int main() {
Node*head = new Node(19);
insertAtBeginning(head, 10);
return 0;
}
Output
10->19->NULL
Explanation
- The line number
15 - 16
is function which insert the node at the beginning of the linked List. - This creates a new node with the data passed and assigns the
head
to the next of the new node.