我想使用游标来构建堆栈,但我真的不了解整个游标实现
public class cursor {
private int header;
static cursorNode[ ] cursor;
private static final int SPACE_SIZE = 100;
static
{
cursor = new cursorNode[ SPACE_SIZE ];
for( int i = 0; i < SPACE_SIZE; i++ )
cursor[ i ] = new cursorNode( null, i + 1 );
cursor[ SPACE_SIZE - 1 ].next = 0;
}
public static int alloc( )
{
int p = cursor[ 0 ].next;
if( p == 0 )
return 0;
cursor[ 0 ].next = cursor[ p ].next;
cursor[ p ].next=0;
return p;
}
public static void free( int p )
{
cursor[ p ].next = cursor[ 0 ].next;
cursor[ 0 ].next = p;
}
public cursor( )
{
header = alloc( );
cursor[ header ].next = 0;
}
public boolean isEmpty( )
{
return cursor[ header ].next == 0;
}
public void addFirst(int l, Object x){
int temp=alloc();
cursor[temp].element=x;
cursor[temp].next=cursor[l].next;
cursor[l].next=temp;
}
public boolean removeFirst(int l){
if(cursor[l].next==0)
return false;
int p =cursor[l].next;
cursor[l].next=cursor[p].next;
free(p);
return true;
}
public void print(int l){
int p=cursor[l].next;
while(p!=0){
System.out.print(cursor[p].element);
p=cursor[p].next;
}
}
}.
public class cursorNode {
Object element;
int next;
public cursorNode(Object x ){
this( x, 0 );
}
public cursorNode(Object x, int n )
{
element = x;
next = n;
}
}
您能解释什么是游标实现以及如何使用它来构建堆栈。 我知道push()将使用addFirst(),而pop()使用removeFirst(),但top()将如何工作。
答案 0 :(得分:0)
首先,解释您发布的代码的作用。它本质上是一种管理存储在固定大小的池中的多个值集合的方法。它的设计使得当从集合中删除项目时,它们将返回到空闲列表以供重用。它在很多方面写得不好,但鉴于你没有要求评论评论,我会跳过它们。
其次,如何使用此代码实现堆栈?答:你不能。没有公共方法来检索值(窥视操作所需),removeFirst
方法返回boolean
而不是删除的值。您需要更改此代码才能使用它来实现堆栈。