如何解决尝试使用while循环打印LinkedList时发生无限循环
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是否有人可以根据我在此处提供的代码理解我的问题,但是我应该怎么做或添加才能使用while循环在LinkedList中正确打印所有值?
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;
}
}
}
所以这是我的“ myLinked”代码,我非常确定没有错误..也许吗?但还是请把它留在这里
我是这里的初学者,非常感谢您的帮助!
public class Node {
Object data;
Node next;
Node(Object obj){
data=obj;
}
}
我的节点代码..这里仅与我一起工作的3个类
解决方法
之所以会这样,是因为last.data
始终等于1。
将while
条件替换为a.current.next != null
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。