forked from codedecks-in/HackerRank-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertAtPositionOfLinkedList.java
More file actions
41 lines (30 loc) · 959 Bytes
/
insertAtPositionOfLinkedList.java
File metadata and controls
41 lines (30 loc) · 959 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
// Complete the insertNodeAtPosition function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int index) {
if (head == null) {
return new SinglyLinkedListNode(data);
}
SinglyLinkedListNode currHead = head;
SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
int count = 0;
if (count == index) {
newNode.next = currHead;
return newNode;
}
while (count < index-1) {
currHead = currHead.next;
count++;
}
SinglyLinkedListNode temp = currHead.next;
currHead.next = newNode;
newNode.next = temp;
return head;
}