Skip to content

Commit fb79cef

Browse files
committed
added LinkedList.java
1 parent ce4d5de commit fb79cef

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

LinkedList.java

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Linked List in Java. Written by Joe James.
2+
public class LinkedList {
3+
Node root;
4+
int size;
5+
6+
public LinkedList() {
7+
root = new Node();
8+
size = 0;
9+
}
10+
11+
// Test code - main function
12+
public static void main(String[] args) {
13+
LinkedList ll = new LinkedList();
14+
System.out.println(ll.getSize());
15+
ll.add(8);
16+
System.out.println(ll.getSize());
17+
ll.add(17);
18+
ll.add(5);
19+
ll.add(10);
20+
System.out.println(ll.find(17).getData());
21+
ll.remove(5);
22+
System.out.println(ll.getSize());
23+
System.out.println(ll.find(5));
24+
}
25+
26+
public void setSize(int s) {
27+
this.size = s;
28+
}
29+
30+
public int getSize() {
31+
return this.size;
32+
}
33+
34+
public Node add(int data) {
35+
Node newNode = new Node(data, root);
36+
this.root = newNode;
37+
this.size++;
38+
return newNode;
39+
}
40+
41+
public Node find(int data) {
42+
Node thisNode = this.root;
43+
44+
while (thisNode != null) {
45+
if (thisNode.getData() == data)
46+
return thisNode;
47+
thisNode = thisNode.getNextNode();
48+
}
49+
return null;
50+
}
51+
52+
public boolean remove(int data) {
53+
Node thisNode = this.root;
54+
Node prevNode = null;
55+
56+
while (thisNode != null) {
57+
if (thisNode.getData() == data) {
58+
prevNode.setNextNode(thisNode.getNextNode());
59+
this.setSize(this.getSize()-1);
60+
return true;
61+
}
62+
prevNode = thisNode;
63+
thisNode = thisNode.getNextNode();
64+
}
65+
return false;
66+
}
67+
68+
// Node class
69+
private class Node {
70+
private Node nextNode;
71+
private int data;
72+
73+
// 0-arg constructor, 1-arg constructor, 2-arg constructor
74+
private Node() { }
75+
76+
private Node(int val) {
77+
data = val;
78+
}
79+
80+
private Node(int val, Node next) {
81+
data = val;
82+
nextNode = next;
83+
}
84+
85+
private void setData(int val) {
86+
this.data = val;
87+
}
88+
89+
private int getData() {
90+
return this.data;
91+
}
92+
93+
private void setNextNode(Node n) {
94+
this.nextNode = n;
95+
}
96+
97+
private Node getNextNode() {
98+
return this.nextNode;
99+
}
100+
}
101+
}

0 commit comments

Comments
 (0)