Java中堆栈的Remove方法
我正在努力解决这个问题-我需要实现一种方法: 公共整数删除(整数n) 我从堆栈中删除最顶端的n个条目。任何关于我可以从哪里着手解决这个问题的建议都将不胜感激 下面是我需要实现这个remove()方法的代码Java中堆栈的Remove方法,java,stack,Java,Stack,我正在努力解决这个问题-我需要实现一种方法: 公共整数删除(整数n) 我从堆栈中删除最顶端的n个条目。任何关于我可以从哪里着手解决这个问题的建议都将不胜感激 下面是我需要实现这个remove()方法的代码 公共类LinkedStack实现StackInterface { 私有节点topNode;//引用链中的第一个节点 公共LinkedStack() { topNode=null; }//结束默认构造函数 公共无效推送(T新条目) { 节点newNode=新节点(newEntry,topNode
公共类LinkedStack实现StackInterface
{
私有节点topNode;//引用链中的第一个节点
公共LinkedStack()
{
topNode=null;
}//结束默认构造函数
公共无效推送(T新条目)
{
节点newNode=新节点(newEntry,topNode);topNode=新节点;
}//端推
公共T peek()
{
T top=null;
if(topNode!=null)
top=topNode.getData();
返回顶部;
}//结束窥视
公共广播电台
{
T top=peek();
if(topNode!=null)
topNode=topNode.getNextNode();
返回顶部;
}//结束弹出
公共布尔值为空(){
返回topNode==null;
}
公共空间清除(){
topNode=null;
}
私有类节点
{
私有T数据;//堆栈中的条目
私有节点下一步;//链接到下一个节点
专用节点(T数据部分)
{
这个(数据部分,空);
}//结束构造函数
专用节点(T数据部分,节点下一个节点)
{
数据=数据部分;
next=nextNode;
}//结束构造函数
私有T getData()
{
返回数据;
}//结束getData
私有void setData(T newData)
{
数据=新数据;
}//结束设置数据
私有节点getNextNode()
{
下一步返回;
}//结束getNextNode
私有void setNextNode(节点nextNode)
{
next=nextNode;
}//结束setNextNode
}//结束节点
}//结束链接堆栈
简单的解决方案就是调用this.pop()
n次。为此,需要使用循环
好像是你的家庭作业,所以我不打算展示代码示例。这是硬件-抱歉,我应该提到这一点,但我只需要一个起点,而你在这方面提供了帮助。谢谢
public class LinkedStack<T> implements StackInterface<T>
{
private Node topNode; // references the first node in the chain
public LinkedStack()
{
topNode = null;
} // end default constructor
public void push(T newEntry)
{
Node newNode = new Node(newEntry, topNode); topNode = newNode;
} // end push
public T peek()
{
T top = null;
if (topNode != null)
top = topNode.getData();
return top;
} // end peek
public T pop()
{
T top = peek();
if (topNode != null)
topNode = topNode.getNextNode();
return top;
} // end pop
public boolean isEmpty() {
return topNode == null;
}
public void clear() {
topNode = null;
}
private class Node
{
private T data; // entry in stack
private Node next; // link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack