【发布时间】:2021-01-25 15:51:50
【问题描述】:
我正在尝试创建一个使用通用节点类的通用堆栈和队列类。它有empty()、pop()、peek()、push() 和search() 方法。我知道有一个内置的Stack 类和堆栈search 方法,但我们必须使用Node 类来实现。
我不确定如何制作search 方法。 search 方法应该返回距堆栈顶部最近的事件的堆栈顶部的距离。最上面的项目被认为在距离 1 处;下一项在距离 2 处;等等
我的课程如下:
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
private Node<E> head;
private int nodeCount;
public static void main(String args[]) {
}
public E peek() {
return this.head.getData();
}
public E pop() {
E item;
item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head==null) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
// todo
}
}
public class Node<E>
{
E data;
Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
public class MyQueue<E> implements QueueInterface<E>
{
private Node<E> head;
private int nodeCount;
Node<E> rear;
public MyQueue()
{
this.head = this.rear = null;
}
public void add(E item){
Node<E> temp = new Node<E>(item);
if (this.rear == null) {
this.head = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public E peek(){
return this.head.getData();
}
public E remove(){
E element = head.getData();
Node<E> temp = this.head;
this.head = this.head.getNext();
nodeCount--;
return element;
}
}
在根据第一条评论处理它之后,我有这个:
public int search(Object o){
int count=0;
Node<E> current = new Node<E> (head.getData());
while(current.getData() != o){
current.getNext();
count++;
}
return count;
}
它没有任何错误,但我无法判断它是否真的正常工作。这看起来正确吗?
【问题讨论】:
-
以
current开头head并调用current=current.getNext()直到current.getData()等于您正在寻找的东西。数一数你这样做的次数。 -
那么 current 会是一个新节点吗?
-
不应该是
public int search(E element)吗? -
@NomadMaker Java 的
Stack#search的签名是public synchronized int search(Object o)。因此,我认为问题中写的是正确的。
标签: java search linked-list stack nodes