スタックの一番上の要素を取得することになっているtop()メソッドに苦労しています。このスタックが空の場合はnullを返し、スタックの一番上の要素を返します。ループを修正するにはどうすればよいですか?
public class Stack<E> implements IStack<E> {
Node head;
public E top() {
if (head == null)
return null;
Node<E> tempNode = head;
for (int i = 0; i < size; i++) {
if (tempNode.getmNextNode() == null) {
tempNode.getmElement();
}
tempNode = tempNode.getmNextNode();
}
return tempNode.getmElement();
}
}
私のノードクラス:
public class Node<E> {
private E mElement;
private Node<E> mNextNode;
Node(E data) {
this.setmElement(data);
}
public E getmElement() {
return this.mElement;
}
public void setmElement(E element) {
this.mElement = element;
}
public Node<E> getmNextNode() {
return this.mNextNode;
}
public void setmNextNode(Node<E> node) {
this.mNextNode = node;
}
}
public E top() {
if (head == null)
return null;
Node<E> tempNode = head;
while(tempNode.getmNextNode()!=null) {
tempNode = tempNode.getmNextNode();
}
return tempNode.getmElement();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加