Here's my implementation of a Singly Linked List. Would appreciate a review.
public class SList<T> {
private Node head;
private int size;
private class Node<T>{
public Node(){
item = null;
next = null;
}
public Node(T item){
this.item = item;
this.next = null;
}
private T item;
private Node next;
}//end of node
//constructor
public SList(){
head = null;
size = 0;
}
public void add(T item){
Node p = new Node(item);
if(head == null){
head = p;
size++;
return;
}
p.next = head;
head = p;
size++;
}
public boolean isEmpty(){
return size == 0;
}
public int getSize(){
return size;
}
public void remove(T item){
Node current = head;
while(current.next != item){
if(current.next == null) {
System.out.println("Item doesn't exist in the list:");
return;
}
current = current.next;
}
current.next = current.next.next;
size--;
}
public void insertAfter(T item1, T item2){
Node current = head;
Node p = new Node(item2);
do{
if(current == null) {
System.out.println("Item doesn't exist in the list:");
return;
}
current = current.next;
}while(current.item != item1);
Node q = current.next;
current.next = p;
p.next = q;
size++;
}
public void insertBefore(T item1, T item2){
Node current = head;
Node p = new Node(item2);
do{
if(current.next == null) {
System.out.println("Item doesn't exist in the list:");
return;
}
current = current.next;
}while(current.next.item != item1);
Node q = current.next;
current.next = p;
p.next = q;
size++;
}
}
this.next = null;
all those null initializes are redundant as Java uses default values for fields. The default value forObject
s isnull.
– Emz 7 hours ago