-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedList.java
More file actions
127 lines (100 loc) · 2.75 KB
/
LinkedList.java
File metadata and controls
127 lines (100 loc) · 2.75 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package src;
// src.LinkedList.java
class Node {
private final int val;
private Node next;
Node() {
val = 0;
}
Node(int val) {
this.val = val;
next = new Node();
}
public int getVal() {
return val;
}
public Node getNextNode() {
return next;
}
public void setNextNode(Node next) {
this.next = next;
}
}
public class LinkedList {
private Node head;
private Node tail;
LinkedList() {
head = tail = null;
}
public boolean isEmpty() {
return (head == null);
}
public void addLast(int item) {
var node = new Node(item);
if (isEmpty()) {
head = tail = node;
} else {
tail.setNextNode(node);
tail = node;
}
}
public void addFirst(int item) {
var node = new Node(item);
if (isEmpty()) {
head = tail = node;
} else {
node.setNextNode(head);
head = node;
}
}
public void removeFirst() {
if (isEmpty()) {
System.out.println("Linked list is empty...");
} else if (head == tail) {
return;
} else {
var secondNode = head.getNextNode();
head.setNextNode(null);
head = secondNode;
}
}
public void removeLast() {
Node currentNode = head;
while (currentNode != null) {
if (currentNode.getNextNode() == tail) {
break;
}
currentNode = currentNode.getNextNode();
}
tail = currentNode;
tail.setNextNode(null);
}
public int indexOf(int item) {
int index = 0;
Node currentNode = head;
while (currentNode != null) {
if (currentNode.getVal() == item) {
return index;
}
currentNode = currentNode.getNextNode();
index++;
}
return -1;
}
public boolean contains(int item) {
return (indexOf(item) != -1);
}
public static void main(String[] args) {
var linkedlist = new LinkedList(); // list items [55, 54, 34, 90]
linkedlist.addFirst(34); // 0 1 2 = 2nd index
linkedlist.addFirst(54); // 0 1 = 1st index
linkedlist.addFirst(55); // 0 = 0th index
linkedlist.addLast(90); // 3 = 3rd index
System.out.println(linkedlist.indexOf(34));
System.out.println(linkedlist.indexOf(54));
System.out.println(linkedlist.indexOf(55));
System.out.println(linkedlist.indexOf(90));
System.out.println(linkedlist.contains(59));
System.out.println(linkedlist.contains(90));
}
}