I don't know if this is a silly question or maybe it's comenscence but my question is I'm creating a Linked List class which contains an add Method
public void addFirst(int data){
node node = new node(data);
if (head == null) {
head = node;
tail = node;
currentSize++;
}
else
node.next = head;
head = node;
currentSize++;
}
} so when i use it like this:
public static void main(String argas[]){
Linkedlist list = new Linkedlist();
list.addFirst(5)
list.addFirst(10)
list.addFirst(15)
list.addFirst(20)
the node that contains 5 has the same name as the node contains 10 and the rest of nodes, how does it works?
The complete code
public class LinkedList {
class node {
int data;
node next;
public node(int data) {
this.data = data;
next = null;
}
public node(){
}
}
private node head;
private node tail;
private int currentSize;
public LinkedList (){
head = null;
currentSize = 0;
}
public void addFirst(int data){
node node = new node(data);
if (head == null) {
head = node;
tail = node;
currentSize++;
}
else
node.next = head;
head = node;
currentSize++;
}
public void addLast(int data){
node node = new node(data);
node tmp = new node();
if (head == null) {
head = node;
tail = node;
currentSize++;
return;
}
tail.next = node;
tail = node;
currentSize++;
return;
}
public void removeFirst(){
if (head == null){
return;
}
if (head == tail){
head = tail = null;
currentSize--;
}
else
head = head.next;
currentSize--;
}
public void removeLast(){
if (head == null){
return;
}
if (head == tail){
head = tail = null;
return;
}
else {
node tmp = new node();
tmp = head;
while (tmp.next != tail){
tmp = tmp.next;
}
tmp.next = null;
tail = tmp;
currentSize--;
}
}
public void printList(){
node tmp = new node();
tmp = head;
while (tmp != null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public void size(){
System.out.println((currentSize));
}
}