java - 遍历 Java 中的链表?

标签 java oop data-structures

我一直在努力观看 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/

相关文章:

c++ - 如何在不进行类型转换的情况下从双端队列中提取?

java - 存储 Java UI 应用程序配置/设置的最佳实践

java - 卡在 wait() 等待线程执行返回

java - 使用 Lenskit 来预测图书评级

c++ - 我的虚函数的原型(prototype)应该是什么?

c - 如何仅使用两个指针来反转单向链表?

java - DOM XML 解析器示例

c# - 为什么要为这个配置类创建一个接口(interface)呢?

php - 为什么静态调用这个方法有效?

javascript - 在 Javascript 中查找两个数组的交集