intgetLen(){ node *p = head;int s =0;while (p !=NULL) { s = s +1; p =p->next; /* code */ }return s;}
Insertion in a Linked List
Insertion in a linked list takes O(1) time.
// Insertion in the beginning of the linked listvoidinsertAtBegin(int val){ node *temp =new node;temp->data = val;if (head ==NULL) { head = temp;temp->next =NULL; }elseif (head !=NULL) {temp->next = head; head = temp; }}// Insertion in the end of the Linked ListvoidinsertAtEnd(int val){ node *temp =new node;temp->data = val;temp->next =NULL;if (head ==NULL) { head = temp; }elseif (head !=NULL) { node *p = head;while (p->next !=NULL) { p =p->next; }p->next = temp; }}
Insertion at any random position of a Linked list
voidinsertAtPos(int pos,int val){if (pos <0|| pos>getLen() ) {return; // If postion does not exits return } node *temp =new node;temp->data = val; node *p = head;int i =0;while (p !=NULL&& i < pos -1) { p =p->next; i++; }temp->next =p->next;p->next = temp;}
Deletion in a Linked list
// Deletion at frontvoiddelAtHead(){ node *p = head;if (head ==NULL) {return; } p =p->next; head = p;}// Deletion at endvoiddelAtTail(){if (head ==NULL) {return; } node *p = head; node *q =NULL;while (p->next !=NULL) { q = p; p =p->next; }q->next =p->next;
Deletion at any random position of a Linked list
voiddelAtPos(int pos){if (pos >getLen() || pos <0) {return; // return if the position is not valid } node *p = head; node *q =NULL;int i =0;while (i < pos) { q = p; p =p->next; i++; }q->next =p->next;}