I created my own implementation of a Singly Linked List. Is there anything I can improve on, in terms of effciency. Also, what other methods would you recommend for me to try and implement. My goal is to just understand the components of basic data structures.
LinkedList:
public class StratchLinkedList {
private Node head;
private int size;
public StratchLinkedList() {
head = null;
size = 0;
}
public void add(Object data) {
Node temp = new Node(data);
Node curr = head;
if (head == null) {
head = temp;
} else {
while (curr.getNext() != null) {
curr = curr.getNext();
}
curr.setNext(temp);
}
}
public void add(Object data, int index) {
Node temp = new Node(data);
Node curr = head;
if (index == 0){
temp.setNext(head);
this.head = temp;
} else{
for(int i = 1; i < index; i++){
curr = curr.getNext();
}
temp.setNext(curr.getNext());
curr.setNext(temp);
}
this.size++;
}
public void replace(Object data, int index) {
Node curr = head;
for (int i = 0; i < 0; i++){
curr = curr.getNext();
}
curr.setData(data);
}
public Object get(int index) {
Node curr = head;
for (int i = 0; i < index; i++){
curr = curr.getNext();
}
return curr.getData();
}
public void remove(int index) {
Node curr = head;
if (index == 0) {
head = head.getNext();
} else {
for (int i = 1; i < index; i++){
curr = curr.getNext();
}
curr.setNext(curr.getNext().getNext());
}
this.size--;
}
public int size() {
return this.size;
}
public String toString() {
String list = "";
list += "[" + this.head.getData() + "]";
Node curr = head.getNext();
while (curr != null){
list += "[" + curr.getData() + "]";
curr = curr.getNext();
}
return list;
}
}
Node:
public class Node {
Node next;
Object data;
public Node(Object data) {
this(data, null);
}
public Node(Object data, Node next) {
this.next = next;
this.data = data;
}
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return this.next;
}
public void setNext(Node nextNode) {
this.next = nextNode;
}
}