Java 链接列表:初始化标题
所以我正在解决一个问题,打印列表最后一个元素的第n个元素 我找到了方法和程序。此过程将查找元素Java 链接列表:初始化标题,java,linked-list,Java,Linked List,所以我正在解决一个问题,打印列表最后一个元素的第n个元素 我找到了方法和程序。此过程将查找元素 public Node nth_element(Node head, int n){ // head to point to the first element in the list // n is the element to be returned from the tail of the list ---do the function here--- } 现在,当我在主类中调用
public Node nth_element(Node head, int n){
// head to point to the first element in the list
// n is the element to be returned from the tail of the list
---do the function here---
}
现在,当我在主类中调用上述方法时。声明上述方法的我的链表类在其构造函数中将head初始化为null
如何初始化头部
这是我的主要课程:
public class Main
{
static void main()
{
List l = new List() //initialize the list
//then i add the elements into the list using insert()
//display()
//now
**Node mynode = l.nth_element(head, value);**
// how do i initialize this head
}
在自定义链表类
列表
中,需要将标题
作为类字段
public class List {
private Node head = null;
// all method for List....
}
然后,当您实现ntheelement
方法时,您不必使用head
作为第一个参数,因为它已经是类成员,您可以直接在类方法中使用它。但如果确实需要,则可以在List
类中创建公共方法:
public Node getHead() {
return head;
}
您的nthement
方法如下所示
public Node nthElement(Node head, int n) {
//implementation ...
}
然后在main方法中,您可以调用ntheelement
like
Node mynode = l.nthElement(l.getHead(), value);
但请确保您的列表不是空的。否则,
head
为null
为@tonga的答案添加了内容
您的类列表构造函数应该类似于:
private Node head;
public List(Node head)
{
this.head = head;
}
然后创建您的列表
List l = new List(new Node(1));
你能给我们看一下你称为主类的类的代码吗?@hemanth在问题中做了一个编辑,你是对的,你应该放下这个类。如果head是一个实例变量,为什么你要将它作为参数从同一个类传递给方法?是的,这就是为什么我说他不需要使用head作为方法的第一个参数。但如果他真的想这样做,那就是一个解决办法。@tonga谢谢你的意见,我知道我错在哪里了。