所以我正在研究从列表的最后一个打印第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---
}
现在,当我在主类中并调用上述方法时。我声明上述方法的Linked List类在其构造函数中将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
}
答案 0 :(得分:1)
在自定义的链接列表类List
中,您需要将head
作为类字段
public class List {
private Node head = null;
// all method for List....
}
然后,当您实现nthElement
方法时,您不必使用head
作为第一个参数,因为它已经是类成员,您可以直接在类方法中使用它。但是如果你确实需要,那么你可以在List
类中创建一个公共方法:
public Node getHead() {
return head;
}
您的nthElement
方法看起来像
public Node nthElement(Node head, int n) {
//implementation ...
}
然后在main方法中,您可以调用nthElement
之类的
Node mynode = l.nthElement(l.getHead(), value);
但请确保您的清单不是空的。否则,head
为null
。
答案 1 :(得分:0)
添加@ tonga的答案。
你的类List构造函数应该是这样的:
private Node head;
public List(Node head)
{
this.head = head;
}
然后创建列表
List l = new List(new Node(1));