-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathCustomLinkedList.java
More file actions
86 lines (70 loc) · 1.67 KB
/
CustomLinkedList.java
File metadata and controls
86 lines (70 loc) · 1.67 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package Programs.LinkedList;
/* Program to implement simple int linked list from scratch */
public class CustomLinkedList {
private Node Head;
private Node Tail;
private int size;
public CustomLinkedList() {
this.size = 0;
}
// Node class with private instance variables and constructors
class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
// insert method which takes the new value as parameter and inserts at the beginning
void insertFirst(int val) {
Node node = new Node(val);
node.next = Head;
Head = node;
if(Tail == null) {
Tail = Head;
}
size++;
}
// traverse method to print all the elements present
public void traverse() {
Node temp = Head;
while(temp != null) {
System.out.print(temp.value + "-> ");
temp = temp.next;
}
System.out.println("END");
}
// insertLast method to insert element at the end of the list
public void insertLast(int val) {
if(Tail == null) {
insertFirst(val);
return;
}
Node node = new Node(val);
Tail.next = node;
Tail = node;
size++;
}
// method to insert the given value at a given index
public void insertAtIndex(int val, int index) {
if(index == 0) {
insertFirst(val);
return;
}
if(index == size) {
insertLast(val);
return;
}
Node temp = Head;
for(int i = 1; i < index && index < size; i++) {
temp = temp.next;
}
Node node = new Node(val, temp.next);
temp.next = node;
size++;
}
}