gpt4 book ai didi

java - 显示链表的第一个节点

转载 作者:行者123 更新时间:2023-11-30 01:58:33 29 4
gpt4 key购买 nike

我能够获取链接列表的第一个值,但它仅适用于这种情况。如何使 getFirst() 能够处理链表中存储的任意数量的值?

该程序输出:第一个数字是 --> 1

public class LinkedListFirst 
{
public static void main(String[] args)
{
MyLinkedList list = new MyLinkedList();
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
list.getFirst();
}
}

class MyLinkedList
{
private class Node // inner class
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null; // initial value is null
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node(); // create new node
newNode.x = d; // init data field in new node
newNode.link = first; // new node points to first node
first = newNode; // first now points to new node
}
//----------------------------------
public void getFirst()
{
System.out.println( "First Number is --> " + first.link.link.x);
}
}

最佳答案

根据您上面的评论,我认为您实际上是在查看列表中的最后一项。

考虑这个方法:

public void getLast()
{
Node current = first;
while(current.link != null){
current = current.link;
}
System.out.println("First number is ---> " + current.x);
}

您的一些困惑可能是由于您对“第一”一词的使用过于宽松。是的,您确实添加了数字 1 第一个,但由于您将项目添加到列表的开头,所以现在它是列表的最后项目列表。

希望对您有所帮助。

关于java - 显示链表的第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622760/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com