Java 为用户定义的堆栈类(链表)编写size()方法
我正在使用链表作为主干来创建自己的通用堆栈数据结构,但我需要创建一个size()方法,类似于堆栈的内置size方法。我不确定使用链表结构的正确方法是什么Java 为用户定义的堆栈类(链表)编写size()方法,java,Java,我正在使用链表作为主干来创建自己的通用堆栈数据结构,但我需要创建一个size()方法,类似于堆栈的内置size方法。我不确定使用链表结构的正确方法是什么 public class LLStack<T> implements StackInterface { private class ListNode { private T data; private ListNode link; public ListNode(T aData, ListNode aLink
public class LLStack<T> implements StackInterface {
private class ListNode
{
private T data;
private ListNode link;
public ListNode(T aData, ListNode aLink)
{
data = aData;
link = aLink;
}
}
private ListNode head;
public LLStack()
{
head = null;
}
public void push(Object data)
{
ListNode newNode = new ListNode((T)data, head);
head = newNode;
}
public T pop()
{
if(head == null)//Empty stack
return null;
T retVal = head.data;
head = head.link;
return retVal;
}
public T peek()
{
if(head == null)
return null;
else
return head.data;
}
public void print()
{
ListNode temp = head;
while(temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}
public int size() {
}
公共类LLStack实现StackInterface{
私有类ListNode
{
私有T数据;
私有列表节点链接;
公共ListNode(T aData,ListNode aLink)
{
数据=aData;
link=aLink;
}
}
私有节点头;
公共LLStack()
{
head=null;
}
公共无效推送(对象数据)
{
ListNode newNode=新ListNode((T)数据,头);
头=新节点;
}
公共广播电台
{
if(head==null)//空堆栈
返回null;
T retVal=head.data;
head=head.link;
返回返回;
}
公共T peek()
{
if(head==null)
返回null;
其他的
返回头数据;
}
公开作废印刷品()
{
ListNode温度=头;
while(temp!=null)
{
系统输出打印LN(温度数据);
温度=温度链接;
}
}
公共整数大小(){
}
基本上与打印方法完全相同
public int size()
{
ListNode temp = head;
int size = 0;
while(temp != null)
{
size += 1;
temp = temp.link;
}
return size;
}
不过,最好存储一个大小字段,该字段会随着每次弹出和推送而更新。我将把它作为练习留给您。如下所示:
在类中保留一个大小变量:
public class LLStack<T> implements StackInterface {
{
private int size;
....
然后使用“获取大小”方法:
public int getSize()
{
return size;
}
有两种简单的方法可以满足您的需求:
public int size() {
ListNode current = head;
int count;
for(count = 0; current != null; count++)
current = current.link;
return count;
}
size
方法只是一种快速获取方法:
public int size() { return this.count; }
您必须修改所有更改大小的方法才能更改此字段的值:
public LLStack() {
this.head = null;
this.count = 0;
}
public void push(T data) {
...
this.count++;
}
public T pop() {
...
this.count--;
return retval;
}
保留大小字段。在大小更改时保持最新。@user2357112您是指附加到我的推送/弹出方法的递增/递减器吗?
public LLStack() {
this.head = null;
this.count = 0;
}
public void push(T data) {
...
this.count++;
}
public T pop() {
...
this.count--;
return retval;
}