Skip to content

Commit 73cdb72

Browse files
committed
Added Java singlylinkedlist implementation
Added Java Singly Linked List implementation files Moved SinglyLinkedList files into respective language folders per instructions in the CONTRIBUTING.md
1 parent e8f615c commit 73cdb72

File tree

7 files changed

+83
-0
lines changed

7 files changed

+83
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
public class Driver {
3+
public static void main(String[] args) {
4+
SinglyLinkedList list = new SinglyLinkedList();
5+
list.add("Test");
6+
list.add("Test 2");
7+
list.add(25);
8+
list.add(27);
9+
System.out.println(list);
10+
}
11+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
public class Node {
3+
private Object content;
4+
Node nextNode;
5+
6+
public Node() {
7+
content = null;
8+
nextNode = null;
9+
}
10+
11+
public Node(Object content) {
12+
this.content = content;
13+
nextNode = null;
14+
}
15+
16+
public Object getContent() {
17+
return content;
18+
}
19+
20+
public Node getNextNode() {
21+
return nextNode;
22+
}
23+
24+
public void setNextNode(Node nextNode) {
25+
this.nextNode = nextNode;
26+
}
27+
28+
public boolean hasNextNode() {
29+
return nextNode != null;
30+
}
31+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
/**
3+
* A generic singly linked list implementation that takes any kind of object.
4+
*/
5+
public class SinglyLinkedList {
6+
Node head;
7+
8+
public SinglyLinkedList() {
9+
head = null;
10+
}
11+
12+
public void add(Object elementContent) {
13+
if (head != null) {
14+
Node temp = new Node(elementContent);
15+
temp.setNextNode(head);
16+
head = temp;
17+
} else {
18+
head = new Node(elementContent);
19+
}
20+
}
21+
22+
// TODO: Needs node deletion method or some way of doing that
23+
24+
public Node getHeadNode() {
25+
return head;
26+
}
27+
28+
@Override
29+
public String toString() {
30+
String result = "";
31+
if (head != null) {
32+
Node currentNode = head;
33+
result += currentNode.getContent();
34+
while (currentNode.hasNextNode()) {
35+
currentNode = currentNode.getNextNode();
36+
result += ", " + currentNode.getContent();
37+
}
38+
}
39+
return result;
40+
}
41+
}

0 commit comments

Comments
 (0)