data structures in java, Exercises of Computer Science

Linked list demonstration in java

Typology: Exercises

2017/2018

Uploaded on 01/20/2018

graciela-aguilar
graciela-aguilar 🇺🇸

1

(1)

2 documents

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
/*
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;
}
}

Partial preview of the text

Download data structures in java and more Exercises Computer Science in PDF only on Docsity!

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; } }