【问题标题】:array-based implementations of list(cursor implementation)列表的基于数组的实现(游标实现)
【发布时间】:2016-04-05 03:24:25
【问题描述】:

我想用游标建栈,但是我真的不明白整个游标实现

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() 怎么用。

【问题讨论】:

  • 我不确定你在问什么。您是否正在寻找对您发布的代码的解释或有关如何实现 top 方法的建议?
  • 我正在寻找两者。但是,如果您现在可以提供一个使用此代码的堆栈,那就太好了。

标签: java arrays stack


【解决方案1】:

首先,解释一下您发布的代码的作用。它本质上是一种管理存储在固定大小的池中的多个值集合的方法。它被设计成当从集合中删除项目时,它们将返回到空闲列表以供重复使用。它在很多方面都写得不好,但鉴于你没有要求审查 cmets,我会跳过它们。

其次,如何使用这段代码来实现堆栈?回答:你不能。没有公共方法来检索值(peek 操作需要),removeFirst 方法返回一个boolean 而不是被删除的值。您需要更改此代码才能使用它来实现堆栈。

【讨论】:

  • 如何实现getFirst()。
  • 您需要向我提供有关您需要帮助的更好的信息。如果您要我编写代​​码,那么我的回答是我不会使用游标类来实现堆栈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
  • 2019-05-27
  • 2012-04-30
  • 2017-07-13
相关资源
最近更新 更多