-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListDesired.java
More file actions
59 lines (54 loc) · 1.38 KB
/
LinkedListDesired.java
File metadata and controls
59 lines (54 loc) · 1.38 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class LinkedListDesired {
public class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
public void addAtDesired(int data, int position) {
Node newNode = new Node(data);
Node i = head;
if (head == null) {
head = newNode;
return;
}
if (head.data == position) {
newNode.next = head;
head = newNode;
return;
}
while (i != null) {
if (i.next != null && i.next.data == position) {
newNode.next = i.next;
i.next = newNode;
return;
}
i = i.next;
}
}
public void printList() {
Node i = head;
while (i != null) {
System.out.print(i.data);
if (i.next != null) {
System.out.print(" -> ");
}
i = i.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkedListDesired lld = new LinkedListDesired();
lld.addAtDesired(1, 0);
lld.printList();
lld.addAtDesired(2, 1);
lld.printList();
lld.addAtDesired(3, 2);
lld.printList();
lld.addAtDesired(4, 1);
lld.printList();
}
}