Delete a Node HackerRank Solution


Delete a Node HackerRank Solution
Source : https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list



Source : https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list


Solution


// Karthikalapati.blogspot.com
/*
Delete Node at a given position in a linked list
Node is defined as
class Node {
int data;
Node next;
}
*/
Node Delete(Node head, int position) {
if (head == null) {
return null;
} else if (position == 0) {
return head.next;
} else {
/* Get Node one element before desired position */
Node n = head;
for (int i = 0; i < position - 1; i++) {
n = n.next;
}
/* Delete Node */
n.next = n.next.next;
return head;
}
}

Insert a node at a specific position in a linked list HackerRank Solution


Insert a node at a specific position in a linked list HackerRank Solution
Source : https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list



Source : https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list


Solution


// Karthikalapati.blogspot.com
/*
Insert Node at a given position in a linked list
First element in the linked list is at position 0
Node is defined as
class Node {
int data;
Node next;
}
*/
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
} else {
/* Get Node one element before desired position */
Node n = head;
for (int i = 0; i < position - 1; i++) {
n = n.next;
}
/* Insert our new Node */
newNode.next = n.next;
n.next = newNode;
return head;
}
}