
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Linked list demonstration in java
Typology: Exercises
1 / 1
This page cannot be seen from the preview
Don't miss anything!

Question: Insert a node at a specific position in a linked list Insert Node at a given position in a linked list head can be NULL First element in the linked list is at position 0 Node is defined as struct Node { int data; struct Node *next; } / Node InsertNth(Node *head, int data, int position) { Node *node = new Node; // create new node to insert and store value node -> data = data;
if (head == NULL) { // if empty just return the new node return node; } else { Node *temp_head = head; // assign head to temp_head to not loose head address int p = 0;
if (position == 0) { // point new node to head and return new node node -> next = head; return node; }
while (temp_head != NULL) { // iterate through the list until position is found if (p == position -1) { node -> next = temp_head -> next; // insert node; point new node to next node temp_head -> next = node; // reconnect prev node to the new node } else { temp_head = temp_head -> next; } p++; } return head; } }