OpenDSA 全教程

Chapter 9 Linear Structures

| 关于   «  8. 栈   ::   目录   ::   10. 空闲链表  »

9. 链接栈

9.1. 链接栈实现

链表栈的实现非常简单。元素仅在列表头部插入和删除。不使用头节点,因为零个或一个元素的列表不需要特殊情况的代码。以下是完整的链表栈实现。

// Linked stack implementation
class LStack implements Stack {
  private Link top;               // Pointer to first element
  private int size;               // Number of elements

  // Constructors
  LStack() { top = null; size = 0; }
  LStack(int size) { top = null; size = 0; }

  // Reinitialize stack
  public void clear() { top = null; size = 0; }

// Put "it" on stack
  public boolean push(Object it) {  
    top = new Link(it, top);
    size++;
    return true;
  }

// Remove "it" from stack
  public Object pop() {           
    if (top == null) return null;
    Object it = top.element();
    top = top.next();
    size--;
    return it;
  }

  public Object topValue() {      // Return top value
    if (top == null) return null;
    return top.element();
  }

  // Return stack length
  public int length() { return size; }
  
  // Check if the stack is empty
  public boolean isEmpty() { return size == 0; }
}
// Linked stack implementation
class LStack<E> implements Stack<E> {
  private Link<E> top;            // Pointer to first element
  private int size;               // Number of elements

  // Constructors
  LStack() { top = null; size = 0; }
  LStack(int size) { top = null; size = 0; }

  // Reinitialize stack
  public void clear() { top = null; size = 0; }

// Put "it" on stack
  public boolean push(E it) {  
    top = new Link<E>(it, top);
    size++;
    return true;
  }

// Remove "it" from stack
  public E pop() {           
    if (top == null) { return null; }
    E it = top.element();
    top = top.next();
    size--;
    return it;
  }

  public E topValue() {      // Return top value
    if (top == null) { return null; }
    return top.element();
  }

  // Return stack length
  public int length() { return size; }
  
  // Tell if the stack is empty
  public boolean isEmpty() { return size == 0; }
}

这是链表栈的可视化表示。

9.1.1. 链接栈压入

Settings

Proficient Saving... Error Saving
Server Error
Resubmit

9.2. 链接栈出栈

Settings

Proficient Saving... Error Saving
Server Error
Resubmit

9.2.1. 基于数组的栈与基于链表的栈比较

基于数组和链式栈实现的所有操作都只需常数时间,因此从时间效率角度来看,两者都没有显著优势。

在实现多个栈时,有时可以利用基于数组的栈的单向增长特性,使用单个数组来存储两个栈。

   «  8. 栈   ::   目录   ::   10. 空闲链表  »

关闭窗口