在我的秋季课程开始之前,我一直在努力观看 YouTube 视频以了解链表,但我不确定如何继续迭代以下链表。“节点”类来自一系列视频(同一作者),但“主要”方法是我编写的。我是否以不合逻辑的方式设计链表(当然,假设一个人不希望使用预定义的 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);
}
}
谢谢您的帮助,
凯特琳