And an array of queue algorithm

Both of which are abstract data types (Abstract Data Type, ADT)
stack comprising two ways in Python, are an array of structures (a List Structure simulation array) and the linked list structure

  • Implement a stack using an array
    design algorithm is simple. However, if the size of the stack itself is changing, and the size of the array can only advance planning and a good statement, the array will be planning a big waste of space, small enough.
    • Determine whether the stack is empty

        def is_empty():
            global top
            if top == -1:  # 顶端
                return True
            else:
                return False
    • Stack

        def push(data):
            global top
            global MAXSTACK  # 堆栈最大容量
            global stack  # stack = [None] * MAXSTACK 声明堆栈
            if top >= MAXSTACK - 1:
                return "堆栈已满"
            else:
                top += 1
                stack[top] = data
    • Pop

        def pop():
            global top
            global stack
            if is_empty():
                return "堆栈是空的"
            else:
                data = stask[top]
                top -= 1
                return data
  • Implement a stack using a linked list
    algorithm complexity. Dynamically changing a length of chain, the effective use of memory resources.

      class Node:
          def __init__(self):
              self.data = 0
              self.next = None
    • Is empty

        def is_empty():
            global top
            if top is None:
                return True
            else:
                return False
    • Stack

        def push(data):
            global top
            new_add_node = Node()
            new_add_node.data = data
            new_add_node.next = top  # 新的数据放在头部
            top = new_add_node
    • Pop

        def pop():
            global top
            if is_empty():
                return "堆栈是空的"
            else:
                ptr = top
                top = top.next  # 从头部删除
                data = ptr.data
                return data
  • Tower of Hanoi
    recursive (repeated + export) + stack.T = 2^n - 1
    1. The n-1 a plate 1 is moved from the 2
    2. The n-th largest plate 3 to move from one
    3. The n-1 2 moves from a plate 3
      def hanoi(n, p1=1, p2=2, p3=3):
          if n == 1:
              print("盘子从 %d 移到 %d" % (p1, p3))
          else:
              hanoi(n-1, p1, p3, p2)
              print('盘子从 %d 移到 %d' % (p1, p3))
              hanoi(n-1, p2, p1, p3)
  • Eight queens problem
    in the board into a new queen, and this position will not be eaten by the queen (not limited to a few cells away: Straight eat, eat horizontal, diagonal inclined to eat), they put the new Queen pushed onto the stack.
    If placed in a new position 8 queen row (or column) have no way to place a new queen (placed in any position will be eaten), the position of a queen ago allowed popped from the stack, and the row ( or column) to find another position again, a new location onto the stack (if not, back to a position before another new queen front-looking line). Back (Backtracking) algorithm.

      global queen
      global number
      EIGHT = 8
      queen = [None] * 8
    
      number = 0
    
      def print_table():
          global number
          x = y = 0
          number += 1
          print('第 %d 组解' % number)
          for x in range(EIGHT):
              for y in range(EIGHT):
                  if x == queen[y]:
                      print('<q>', end='')
                  else:
                      print('<->', end='')
              print('')
          input('\n..按下任意键继续..\n')
    
      def attack(row, col):
          global queen
          i = 0
          atk = 0
          offset_row = offset_col = 0
          while atk != 1 and i < col:
              offset_col = abs(i - col)
              offset_row = abs(queen[i] - row)
              if queen[i] == row or offset_row == offset_col:
                  atk = 1
              i += 1
          return atk
    
      def decide_position(value):
          global queen
          i = 0
          while i < EIGHT:
              if attack(i, value) != 1:
                  queen[value] = i
                  if value == 7:
                     print_table()
                  else:
                      decide_position(value+1)
              i += 1
    
      decide_position(0)
  • Queue with an array of
    simple algorithm. Shortcoming array size can not be dynamic application according to the actual needs of the queue, you can only declare a fixed size.
    With two front and rear pointers to point to the front and end of the queue.

      NAXSIZE = 4
      queue = [0] * MAXSIZE
      front = -1
      rear = -1
    An element is added, the added value of a rear;
    removal of one element, the front value plus 1.
    rear = MAXSIZE - 1, indicates that the queue is full.
    • The team

        def enqueue(item):
            global rear
            global front
            global queue
            if rear == MAXSIZE - 1:
                print('队列已满')
            else:
                rear += 1
                queue[rear] = item  # 将新数据加到队列的末尾
    • The team

        def dequeue():
            global rear
            global front
            global queue
            global MAXSIZE
            if front == rear:
                print('队列已空')
            else:
                front += 1
                item = queue[front]
    • The first team return value

        def front_value():
            global rear
            global front
            global queue
            if front == rear:
                print('这是空队列!')
            else:
                print(queue[front])
  • Queue as a linked list
    • The team

          def enqueue(item):
              global front
              global rear
              new_data = Node()
              new_data.value = item
              if rear == None:
                  front = new_data
              else:
                  rear.next = new_data  # 将新元素连接到队列末尾
              rear = new_data  # 将 rear 指向新元素,这是新队列的队尾
              new_data.next = None
    • The team

        def dequeue():
            global front
            global rear
            if front == rear:
                print('队列已空')
            else:
                front = front.next
  • Two-way queue (Double Ended Queues, deque)
    Lfront, Lrear
    Rfront, Rrear
    • One end of the addition, both ends removed

        def enqueue(value):
            global front
            global rear
            node = Node()
            node.data = value
            node.next = None
            if rear == None:  # 检查是否为空队列
                front = node
            else:
                rear.next = node  # 将节点加入到队列的末尾
            rear = node  # 将尾指针指向新加入的节点
        def dequeue(action):
            global front
            global rear
            # 从前端取出数据
            if not(front == None) and action == 1:
                if front == rear:
                    rear = None
                value = front.data
                front = front.next
                return value
            # 从队列末尾取出
            elif not(rear == None) and action == 2:
                startNode = front
                value = rear.data
                # 查找队列末尾节点的前一个节点
                tempNode = front
                while front.next != rear and front.next != None:
                    front = front.next
                    tempNode = front
                front = startNode  # 新前端指针
                rear = tempNode   # 新尾端指针
                # 队列中仅剩下最后一个节点时,取出后将 front 和 rear 指向 None
                if front.next == None or rear.next == None:
                    front = None
                    rear = None
                return value
            else:
                return -1
    • Add ends, one end removed
  • Priority queue (Priority Queue)
    if the element can optionally be added, but the higher priority to the output (HPOF, Highest Priority Out First)
    when each of the input element according to the priority order, is common queue. In terms of the input reverse order of the priority order, it is stacked.

Common application stack:

  1. Traversing the binary tree computing and forests, e.g. preorder Inorder, preorder traversal Preorder like.
  2. The computer central processing unit interrupt processing Interrupt Handling.
  3. DFS graph depth-first search.
  4. Some so-called computer stack Stack Computer, using the empty address zero-address instruction, the instruction no operands, and most are pressed by the pop Pop Push two instructions handlers.
  5. Recursive procedure call and return. Before each recursion, the address must first variable and a command value is saved on the stack. When returning from the recursion, then sequentially taken out from the top of the stack these correlation values, return to the original state before performing a recursive, then down to continue.
  6. Conversion and arithmetic expression evaluation, for example to a subsequent conversion process sequential method.
  7. Subroutine call and return processing, for example, before execution of a subroutine call, you must first return address (the address of the next instruction) pushed onto the stack, and then begin execution of a subroutine call operation, until after the subroutine is finished, in the pop return address from the stack.
  8. Compile Error Handling Compiler Syntax Processing. For example, when an error or warning message compilation process occurs, where the address will be pushed onto the stack, then the table will show error messages.

Stack: the same set of a set of data types, all operations are performed at the top of the stack, with the "last out" characteristics.

Queue of applications:

  1. Figure breadth-first search BFS
  2. Analog computer
  3. Job scheduling of CPU
  4. Line concurrent processing system external apparatus

Guess you like

Origin www.cnblogs.com/catyuang/p/11760499.html