-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathSolution.java
More file actions
42 lines (37 loc) · 820 Bytes
/
Solution.java
File metadata and controls
42 lines (37 loc) · 820 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
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
class Node {
int data;
Node next;
}
*/
/**
(1, 0) -> null
*/
Node InsertNth(Node head, int data, int position) {
Node current = head;
Node prev = head;
int counter = 0;
Node node = new Node();
node.data = data;
if (head != null && position == 0) {
node.next = head;
return node;
}
if (head == null) { return node; }
while (counter < position && current.next != null) {
prev = current;
current = current.next;
counter++;
}
if (counter != position) {
current.next = node;
} else {
prev.next = node;
node.next = current;
}
return head;
}