Inserting a Node
Procedure to insert a new node in the beginning, end or at a specific position in the linked list.
Insert at Beginning :
void insertAtBeginning(struct node *ptr, int data) {
// Creating a new node
struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));
newNode -> data = data;
// Make the new node as first node
newNode -> next = head;
head = newNode;
}Insert at N-th Position :
void insertAtNthPos(struct node *ptr, int pos, int data) {
// If position is invalid
if (pos < 0 || pos > count(head)) {
printf("Inavlid position\n");
return;
}
else {
// Creating a new node
struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));
newNode -> data = data;
// For valid position, traverse to the position
for (int i = 0; i < pos - 2; i++) {
ptr = ptr -> next;
}
// Setting up links
newNode -> next = ptr -> next;
ptr -> next = newNode;
}
}Insert at End in O(1) Time :
Insert at End in O(n) Time :
Contributed by Nitin Ranganath
Last updated
Was this helpful?