Linear Structures-stacks, queues

线性数据结构有两端:有左右、前后、顶底等叫法。

栈(Stack):是一个项的有序集合。添加和移除项的操作都在同一端,该端通常被称作顶(top),另一端为底(base)。

遵循后进先出(LIFO)原则,即越新的项越靠近顶,反之越靠近底。如叠起来的盘子,书,或浏览网页时(实际是指网址),打开第一个,二个,三个网页,当后退时,顺序是三,二,一。

栈的操作:

  • Stack() creates a new stack that is empty. It needs no parameters(参数) and returns an empty stack.
  • push(item) adds a new item to the top of the stack. It needs the item and returns nothing.
  • pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified(修改).
  • peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified.
  • isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value.
  • size() returns the number of items on the stack. It needs no parameters and returns an integer.

python实现:

class Stack:
     def __init__(self):
         self.items = []

     def isEmpty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)

例:

      

队列(Queue)是项的有序集合,新项在一端加入,该端为队尾(rear),已有项移除发生在另一端,该端为队首(front)。项从队尾进入队列后开始向队首前进,直至成为下一个要被移除的项。遵循先进先出原则(FIFO)或叫做先到先服务。如排队买饭,银行排队等服务,打字时键盘敲击信号被存储在类似队列的缓冲区中,最终以正确顺序显示在屏幕上。

  • Queue() 创建一个空队列,不需要参数并且返回一个空队列
  • enqueue(item) 添加一个新项到队列的rear,无返回值
  • dequeue() 从队列中移除队首项并返回该项,不需要参数,队列被修改
  • isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value.
  • size() returns the number of items in the queue. It needs no parameters and returns an integer.

python实现:

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

例:

      

渐变 --> 突变
原文地址:https://www.cnblogs.com/lybpy/p/7906821.html