《算法和数据结构》之栈

1:基本概念

栈类似于生活中的死胡同,遵循后入先出的原则,即LIFO(Last In First Out)。

/**
* The Stack class represents a last-in-first-out
* (LIFO) stack of objects. It extends class Vector with five
* operations that allow a vector to be treated as a stack. The usual
* push and pop operations are provided, as well as a
* method to peek at the top item on the stack, a method to test
* for whether the stack is empty, and a method to search
* the stack for an item and discover how far it is from the top.
*


* When a stack is first created, it contains no items.
*/

2:源码中包含的方法(以JDK1.8为例)

这里写图片描述

  1. 构造方法,创造一个空栈:Stack()
  2. 判断是否为空栈:boolean empty()
  3. 返回栈顶元素,注意这里不删除任何元素:T peek()
  4. 删除栈顶元素,并将删掉的栈顶元素作为返回值返回:T pop()
  5. 将一个元素压入栈顶:void push()
  6. 返回一个元素距离栈顶的距离:int search(Object)

3: 栈的链表实现

我们首先定义一个内部类来保存每个链表的节点,该节点包括当前的值以及指向下一个的值,然后建立一个节点保存位于栈顶的值以及记录栈的元素个数;

class Node {
    public T Item{get;set;}
    public Node next{get;set;}
}
private Node first = null;
private int number = 0;

Push方法的实现思路:因为栈的压入只能通过栈顶,所以在push之前,需要先将原来的栈顶元素保存,再新建一个栈顶元素,并把该元素的下一个节点指向原有的栈顶元素。
这里写图片描述

示例代码:

void push(T node){
    Node oldFirst = first;
    first = new Node();
    first.item = node;
    first.next = oldFirst;
    number++;
}

Pop方法的实现思路:首先保存栈顶元素的值,即旧的栈顶元素,然后将栈顶元素设置为该元素的下一个元素,并返回保存的旧的栈顶元素。

这里写图片描述

示例代码:

T pop(){
    T item = first.item;
    first = first.next;
    number--;
    return item;
}

猜你喜欢

转载自blog.csdn.net/maohoo/article/details/81287422