我一直在努力观看 YouTube 视频,以便在秋季类(class)开始前理解链表,但我不确定如何继续迭代以下链表。 “节点”类来自一系列视频(同一作者),但“主要”方法是我编写的。我是不是以一种不合逻辑的方式来设计链表(当然假设一个人不希望使用预定义的 LinkedList 类,因为教授希望我们每个人都编写自己的实现)?:
class Node
{
private String data;
private Node next;
public Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}
public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}
public static int size(Node list)
{
int count = 0;
while (list != null)
{
count++;
list = list.getNext();
}
return count;
}
}
public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);
}
}
感谢您的帮助,
凯特琳
最佳答案
如其他一些评论所述,您的链接列表中存在一些缺陷。但是你在那里有了一个良好的开端,它掌握了链表的概念并且看起来很实用。要回答关于如何循环链表的这个特定实现的基本问题,您可以这样做
Node currentNode = n1; // start at your first node
while(currentNode != null) {
// do logic, for now lets print the value of the node
System.out.println(currentNode.getData());
// proceed to get the next node in the chain and continue on our loop
currentNode = currentNode.getNext();
}
关于java - 遍历 Java 中的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18249576/