import java.util.*;
public class testMain {
public static void main(String[] args){
myLinked a = new myLinked();
a.insertAtFront(1);
a.insertAtFront(2);
a.insertAtFront(3);
a.insertAtFront(4);
a.insertAtFront(5);
System.out.println(a.getFirst());
while (a.last.data != null) {
System.out.println(a.getNext());
}
}
}
idk if anyone would understand my problem base on the code i gave here, but what should i do or add in order to print all the values properly in LinkedList using while loop?
public class myLinked {
Node first, last,current ;
public myLinked(){
}
public void insertAtFront(Object insertItem){
Node newNode = new Node(insertItem);
if( first == null ){
first = newNode;
last = newNode;
}else
{
newNode.next = first;
first = newNode;
}
}
public Object removeFromFront(){
Object removeItem = null;
if (first == null){
return removeItem;
}
removeItem = first.data;
if ( first == last){
first = null;
last = null;
}else
first = first.next;
return removeItem;
}
public void insertAtBack(Object insertItem){
Node newNode = new Node(insertItem);
if (first == null){
first = newNode;
last = newNode;
}else
{
last.next = newNode;
last = newNode;
}
}
public Object removeFromBack(){
Object removeItem = null;
if (first == null){
return removeItem;
}
removeItem = last.data;
if ( first == last){
first = null;
last = null;
}else
{
current = first;
while (current.next != last)
current = current.next;
last = current;
last.next = null;
}
return removeItem;
}
public Object getFirst(){
if (first == null)
return null;
else{
current = first;
return current.data;
}
}
public Object getNext(){
if (current == last)
return null;
else{
current = current.next;
return current.data;
}
}
}
So heres my "myLinked" code that Im pretty sure no error..maybe? but ill leave it here anyway
Im beginner here so ill really appreciate for you help! <3
public class Node {
Object data;
Node next;
Node(Object obj){
data=obj;
}
}
my node code..theres only 3 class here that im working with
a.getNext()doesn't changea, so ifa.last.data != nullwas true the first time, it will be true forever (thus, infinite loop). And anyway,ais your list, so you don't ever want it to change. You need another variable that you can step from item to item in the list.