Sword finger offer note 8: data structure summary (Python)

Sword finger offer note 8: summary of data structure (p37-72)



An array is the data that occupies a block of continuous memory and is stored sequentially. In Python, arrays are usually represented by lists. The array can be read and written in O(1) time, and the array represented by list in Python also saves the trouble of moving other elements when inserting / deleting. In addition, we can use the relationship between array subscripts and elements to implement a simple hash table.

Representation of one dimensional array

One dimensional array represented by list

>>>arr1 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

One dimensional array represented by numpy

>>>import numpy as np
>>>arr2 = np.asarray(arr1)
array([1, 2, 3, 4, 5])

You can see the difference between arrays represented by lists and arrays represented by numpy

[1, 2, 3, 4, 5]
[1 2 3 4 5]

It is not allowed to use numpy, such as leetCode, so the following is not an example of numpy. For the usage of numpy, please refer to NumPy tutorial | rookie tutorial

Representation of two dimensional array

The following is an array with two rows and three columns

>>>arr3 = [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

Basic operation of array

Here are some basic operations about arrays, which are basically the basic operations of lists in python. For more information, please refer to Python 3 list - rookie tutorial
For example, one-dimensional array is used. If the operation of two-dimensional array is similar, it is not written

Array size

One-dimensional array


Two dimensional array rows


Number of columns in 2D array


Array read and write

>>>arr1[2] = 0
[1, 2, 0, 4, 5]

Last element in array


Array insertion

>>>arr1.insert(2, 9)
[1, 2, 9, 0, 4, 5]

Array tail insertion

[1, 2, 9, 0, 4, 5, 8]

Array deletion

[1, 2, 9, 0, 4, 5, 8]
>>>del arr1[2]
[1, 2, 0, 4, 5, 8]

Take the last element of the array and delete it

[1, 2, 0, 4, 5, 8]
>>>a = arr1.pop()
[1, 2, 0, 4, 5]

Character string

There is no end mark for strings in Python, and the operation is not as complicated as c language. Here is a complete Python 3 string tutorial Python 3 string rookie tutorial , I won't write more.

Linked list

A linked list is a chain structure that links many single nodes with a pointer. In Python, you need to construct the node type of a linked list.

Single chain table node type

The node type of single chain table only needs two parts, one is the node value, the other is the pointer to the next node.

class ListNode:
    # Link list node definition
    def __init__(self, x):
        self.val = x
        self.next = None

Create a single chain table

Here is the code that initializes the list into a single chain table and returns the header pointer of the single chain table.

class LinkList(object):
    # Initialization of linked list
    def __init__(self):
        self.head = 0

    # Initialize list as linked list
    def initlist(self, items):
        self.head = ListNode(items[0])
        # Define the header pointer first, that is, its value is the first element in items
        p = self.head
        # Set a move pointer to add the next elements of items in a single chain table
        for item in items[1:]:
            # Traverse the remaining elements in items
            node = ListNode(item)
            # Create a new listNode type for the element
            p.next = node
            # Move p pointer
            p = p.next
        return self.head

Two fork tree

In a binary tree, each node has at most two children. In Python, you need to construct a node type of binary tree.

Node type of binary tree

The node type of binary tree includes three parts: node value and pointer of left and right child nodes.

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

Basic operation of binary tree

There are many contents of binary tree, I intend to brush the whole book to make a systematic summary of binary tree. Only a brief overview is given here.

Traversal of binary tree

  1. Preorder traversal: root → left → right
  2. Middle order traversal: left → root → right
  3. Backward traversal: left → right → root
  4. Breadth first traversal (breadth first traversal): from top to bottom, from left to right

Building a binary tree

Here are the previous notes, which include the code to build a binary tree according to the middle order traversal and the first order traversal and the code to build a binary tree according to the middle order traversal and the second order traversal.
Sword finger offer note 4: rebuilding a binary tree (Python)

Deformation of binary tree

Balanced binary tree, binary search tree, binary sort tree, Huffman tree, large and small top heap

Other tree structure

B tree and B+ tree

Stack and queue


The stack is characterized by last in, first out, like a tube for badminton. In Python, use lists to mimic stacks. The stack pressing operation is to insert at the end of the list, and the pop-up operation is to delete the last element of the list (I've seen the operation in the list header, but I think it's easier to operate at the end of the list).

Basic operation of stack

class Stack:
    # Definition of stack
    def __init__(self):
        self.items = []

    # Stack, equivalent to inserting at the end of the list
    def push(self, item):

    # Pop stack, same as pop() method of list
    def pop(self):
        return self.items.pop()

    # Judge whether the stack is empty
    def is_empty(self):
        return self.size() == 0

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

    # Returns the top element of the stack, the last element in the list
    def peak(self):
        return self.items[-1]


The characteristics of queues are first in, first out. In Python, lists are used to simulate the operation of queues. To join a team is to insert after the list, and to leave a team is to delete the list header.

Basic operation of queue

class Queue:
    # Definition of queue
    def __init__(self):
        self.items = []

    # Team entry, equivalent to inserting at the end of the list
    def en_que(self, item):

    # Out of line, i.e. delete the first element in the list and return it
    def un_que(self):
        elem = self.items[0]
        self.items = self.items[1:]
        return elem

    # Judge whether the queue is empty
    def is_empty(self):
        return self.size() == 0

    # Size of the queue
    def size(self):
        return len(self.items)

    # Returns the last element in the list
    def tail(self):
        return self.items[-1]

Knowledge map of data structure

Here is a summary based on the undergraduate textbook (below)

Published 8 original articles, won praise 0, visited 61
Private letter follow

Tags: Python C

Posted on Thu, 12 Mar 2020 04:25:30 -0400 by ez5527