我在此分配方面有一个小问题:我想完成LinkedStack的实现,并确保按Stack接口中的定义实现peek,isEmpty和size方法。我相信我大部分都可以正常工作(虽然还没有测试过),但是我在ToString方法中遇到了一个障碍
这是讲师提供的启动服务
public interface Stack<T> {
/**
* Adds the specified element to the top of this stack.
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
* @return the element removed from the stack
*/
public T pop();
/**
* Returns without removing the top element of this stack.
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
* @return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
* @return a string representation of the stack
*/
public String toString();}
这是我的LinkedStack类代码:
public class LinkedStack<T> implements Stack<T> {
private Node head; //the head node
private int size; // number of items
private class Node {
T item;
Node next;
}
public LinkedStack() {
head = null;
size = 0;
}
public boolean isEmpty() { return (size == 0); }
public T pop() {
T element = head.item;
head = head.next;
size--;
return element;
}
public void push(T element) {
Node oldHead = head;
head = new Node();
head.item = element;
head.next = oldHead;
size++;
}
public int size() { return size; }
public T peek() {
if (isEmpty()) throw new NoSuchElementException("Error: Stack underflow");
return head.item;
}
public String toString() {
StringBuilder string = new StringBuilder();
for (T stack : this) {
string.append(stack + " ");
}
return string.toString();
}}
从中我得到每个错误不适用于所需的表达式类型:array或java.lang.Iterable找到:edu.csuniv.isiahjohnson.LinkedStack
我是否需要Iterator对象作为堆栈项,或者这仅适用于LinkedList类?
这是一个解决方案。它没有实现Iterable
,但只是迭代节点。而且我还删除了最后一个空格。代替StringBuilder
您可以使用StringJoiner
Java 8以来存在的。
@Override
public String toString() {
final StringBuilder string = new StringBuilder();
Node node = this.head;
while (node != null) {
string.append(node.item).append(' ');
node = node.next;
}
// remove last space:
if (string.length() > 0)
string.setLength(string.length() - 1);
return string.toString();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句