Я не могу заставить работать печать и добавление в LinkedList, как сейчас.
Когда я добавляю один или два узла, все работает нормально.Более того, он не работает должным образом.
Например: добавление 4 и 3 с добавлением первого
3-> 4 ->
Но когда я добавляюеще один, вот что я получаю:
2-> 3-> 3 ->
Может кто-нибудь сказать мне, с этим дело.Я довольно новичок в программировании.
public class LinkedListPractice{
public static void main(String[]args){
//add items to the LinkedList
GenericLinkedList<Integer> gLink = new GenericLinkedList<>();
gLink.addFirst(4);
gLink.addFirst(3);
gLink.addFirst(2);
gLink.addFirst(1);
gLink.printList();
}//main method
} //LinkedListPractice
class GenericLinkedList<E>{
int size; //represents number of nodes in the LinkedList
Node<E> head;
public GenericLinkedList(){
size = 0;
head = null;
} //GenericLinkedList no parameter constructor
//printList
public void printList(){
Node<E> current = head;
for(int i = 0; i < size; i++){
System.out.print(current.getData() + "->");
current = head.next;
} //for
} //printList
public void addFirst(E element){
Node<E> newNode = new Node<E>(element);
if(head == null){head = newNode;}
else{
newNode.next = head;
head = newNode;
}
size++;
} //addFirst
public boolean isEmpty(){
if(head == null){
return true;
}else
return false;
} //isEmpty
//inner node class
private static class Node<E>{
//private data fields
private E data;
private Node<E> next; //represents the next link in the LinkedList
public Node(E element){
data = element;
next = null;
} //Node class constructor
public E getData(){
return data;
} //getData
} //Node class
} //GenericLinkedList