如何返回Node类型的值?

时间:2017-07-02 04:45:10

标签: java generics types nodes

我试图使用Stack类完成peek方法。我试图返回顶部元素的值。

public class stack<T> implements StackInt<T>
{
     Node<T> root;     
     public boolean isEmpty()
     {   
         Node<T> top = root;
         if( top == null)
         {
            return true;
         }
         return false;
     }

public T peek() throws EmptyStackException
     {
         Node<T> top = root;
         if(isEmpty())
         {
            throw new EmptyStackException("stack underflow");
         }
         return top.val;
     }
}

当我编译它时会给我一个错误:

stack.java:34: error: cannot find symbol
         return top.val;
                   ^
  symbol:   variable val
  location: variable top of type Node<T>
  where T is a type-variable:
    T extends Object declared in class stack

这是Node类:

public class Node<T>
{
   T data;
   Node<T> next;

   public Node( T data, Node<T> next )
   {
      this.data = data;
      this.next = next;
   }

   public String toString()
   {
      return "" + this.data;
   }
}

我的语法错误是什么?我试图使用Nodes来创建peek / push / pop方法。但我必须在我的代码中使用泛型类型。

谢谢

1 个答案:

答案 0 :(得分:1)

datanext设为私有并添加getter

public class Node<T> {
    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() {
        return this.data;
    }

    public Node<T> getNext() {
        return this.next;
    }

    public String toString() {
        return "" + this.data;
    }
}

使用:top.getData();