我对此作业有轻微问题: 我想完成LinkedStack实现并确保peek,isEmpty和size方法按Stack接口中的定义实现。 我相信我已经使大部分工作正常(虽然还没有测试过)但是我遇到了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();
}}
从此我得到了错误 for-each不适用于表达类型 required:array或java.lang.Iterable 发现:edu.csuniv.isiahjohnson.LinkedStack
我是否需要堆栈项的Iterator对象,或者这只适用于LinkedList类?
答案 0 :(得分:1)
如果你想在java中使用每个循环,你的对象需要实现Iterable
接口。
在java中,这段代码:
for (T stack : this) {
...
}
是一个语法词汇:
for(Iterator<T> iter = this.iterator(); iter.hasNext(); ) {
T item = iter.next();
...
}
很明显,你需要iterator()
来做到这一点,因此 - 实施Iterable
答案 1 :(得分:0)
这是一个解决方案。它没有实现Iterable
,但它只是迭代节点。我也删除了最后一个空格。您可以使用自{8}以来存在的StringBuilder
而不是StringJoiner
。
@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();
}