我使用链表作为主干来制作我自己的通用堆栈数据结构但是我需要制作一个类似于堆栈的内置大小方法的size()方法。我不确定使用链接列表结构的正确方法吗?
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() {
}
答案 0 :(得分:0)
它与打印方法基本相同。
public int size()
{
ListNode temp = head;
int size = 0;
while(temp != null)
{
size += 1;
temp = temp.link;
}
return size;
}
尽管如此,存储随每次弹出和推送更新的大小字段更为理想。我会把它作为锻炼给你。
答案 1 :(得分:0)
像这样:
在班级中保留一个大小变量:
public class LLStack<T> implements StackInterface {
{
private int size;
....
在push和pop方法中,递增/递减大小:
public void push(Object data)
{
ListNode newNode = new ListNode((T)data, head);
head = newNode;
size ++;
}
public T pop()
{
if(head == null)//Empty stack
return null;
size --;
T retVal = head.data;
head = head.link;
return retVal;
}
然后有一个get size方法:
public int getSize()
{
return size;
}
答案 2 :(得分:0)
有两种简单的方法可以做你想做的事:
每次调用方法时,通过执行端到端遍历来计算列表。这将是缓慢的,我不会在一个说明性的例子之外推荐它。这样您就不需要将大小存储为字段:
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;
}