Implement insertion of node at any position in liked list in C++
Code
#include <iostream>using namespace std;class Node{public:int data;Node *next;};void insertany(Node **head, int data, int position){Node *newnode = new Node();newnode->data = data;newnode->next = NULL;if (*head == NULL){*head = newnode;return;}Node *current = *head;if (position == 0){newnode->next = current;*head = newnode;return;}for (int i = 0; i < position - 1; i++){current = current->next;}newnode->next = current->next;current->next = newnode;}void printlist(Node *head){while (head != NULL){cout << head->data << " ";head = head->next;}}int main(){Node *head = NULL;insertany(&head, 1, 3);insertany(&head, 4, 0);insertany(&head, 2, 2);insertany(&head, 6, 1);insertany(&head, 2, 4);printlist(head);}
Output
4 6 1 2 2
0 Comments
Post a Comment