-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInserNodeInLL.java
More file actions
44 lines (33 loc) · 811 Bytes
/
InserNodeInLL.java
File metadata and controls
44 lines (33 loc) · 811 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
43
44
public class InserNodeInLL {
}
class Node<T> {
T data;
Node<T> next;
public Node(T data) {
this.data = data;
}
}
class Solution {
public static Node<Integer> insert(Node<Integer> head, int pos, int data) {
// Your code goes here
if (head == null) {
return head;
}
Node<Integer> newNode = new Node<>(data);
if (pos == 0) {
newNode.next = head;
return newNode;
} else {
Node<Integer> prev = head;
while (pos > 1 && prev != null) {
prev = prev.next;
pos--;
}
if (prev != null) {
newNode.next = prev.next;
prev.next = newNode;
}
}
return head;
}
}