Implementation methods of eight common data structures in python (recommended Collection)

Time:2020-1-17

As a required part of computer foundation, data structure is also a necessary test for many large Internet enterprises. It is conceivable that it is important in the field of computer.

However, many students majoring in computer only understand the theory of data structure, but they can’t realize all kinds of data structures with code.

Stack

class Stack(object):
    def __init__(self, limit=10):
        Self.stack = [] store element
        Self.limit = limit - stack capacity limit
    Def push (self, data): determine whether the stack overflows
        if len(self.stack) >= self.limit:
            print('StackOverflowError')
            pass
        self.stack.append(data)
    def pop(self):
        if self.stack:
            return self.stack.pop()
        else:
            Raise indexerror ('pop from an empty stack ') (empty stack cannot be popped
    Def Peek (self): view the top most element of the stack
        if self.stack:
            return self.stack[-1]
    DEF is "empty (self):" judge whether the stack is empty or not "
        return not bool(self.stack)
    Def size (self): returns the stack size
        return len(self.stack)

Single linked list

class Node:  
    def __init__(self, data):
        self.data = data  
        self.next = None  
class Linked_List:
    def __init__(self):
        self.head = None
    Definition initlist (self, data list): ා list initialization function
        Self. Head = node (data list [0]) to create a head node
        temp=self.head
        For I in Data menu [1:]: create nodes and chain lists for data one by one
            node=Node(i)
            temp.next=node
            temp=temp.next
    DEF is "empty (self):" judge whether the list is empty "
        if self.head.next==None:
            print("Linked_list is empty")
            return True
        else:
            return False
    Def get? Length (self):? Get the length of the linked list
        Temp = self.head temporary variable points to the queue head
        Length = 0 × calculate the length variable of the linked list
        while temp!=None:
            length=length+1
            temp=temp.next
        Return length
    Def insert (self, key, value): ා linked list insert data function
        if key<0 or key>self.get_length()-1:
            print("insert error")
        temp=self.head
        i=0
        While I < = key: ා after traversing to find the node whose index value is key, insert the node after it
            pre=temp
            temp=temp.next
            i=i+1
        node=Node(value)
        pre.next=node
        node.next=temp
    Def print list (self): traverses the linked list and prints out the elements in turn
        print("linked_list:")
        temp=self.head
        new_list=[]
        while temp is not None:
            new_list.append(temp.data)
            temp=temp.next
        print(new_list)
    Def remove (self, key): ා linked list delete data function
        if key<0 or key>self.get_length()-1:
            print("insert error")
        i=0
        temp=self.head
        While temp! = none: traverse to find the node whose index value is key
            pre=temp
            temp=temp.next
            i=i+1
            if i==key:
                pre.next=temp.next
                temp=None
                return True
        pre.next=None
    Def reverse (self): reverse the list
        prev = None
        current = self.head
        while current:
            next_node = current.next
            current.next = prev
            prev = current
            current = next_node
        self.head = prev

Double linked list

class Node(object):
    #Python learning exchange QQ group: 857662006 
    #Double linked list node
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None
class DLinkList(object):
    #Double linked list
    def __init__(self):
        self._head = None
    def is_empty(self):
        #Judge whether the list is empty
        return self._head == None
    def get_length(self):
        #Return the length of the linked list
        cur = self._head
        count = 0
        while cur != None:
            count=count+1
            cur = cur.next
        return count
    def travel(self):
        #Ergodic list
        cur = self._head
        while cur != None:
            print(cur.item)
            cur = cur.next
        print("")
    def add(self, item):
        #Head insert element
        node = Node(item)
        if self.is_empty():
            #If it is an empty linked list, point to node
            self._head = node
        else:
            #Point the next of the node to the header node of the head
            node.next = self._head
            #Point prev of head node of head to node
            self._head.prev = node
            #Point to node
            self._head = node
    def append(self, item):
        #Tail insert element
        node = Node(item)
        if self.is_empty():
            #If it is an empty linked list, point to node
            self._head = node
        else:
            #Move to the end of the list
            cur = self._head
            while cur.next != None:
                cur = cur.next
            #Point the next of tail node cur to node
            cur.next = node
            #Point prev of node to cur
            node.prev = cur
    def search(self, item):
        #Find if the element exists
        cur = self._head
        while cur != None:
            if cur.item == item:
                return True
            cur = cur.next
        return False
    def insert(self, pos, item):
        #Add node at specified location
        if pos <= 0:
            self.add(item)
        elif pos > (self.length()-1):
            self.append(item)
        else:
            node = Node(item)
            cur = self._head
            count = 0
            #Move to the previous location in the specified location
            while count < (pos-1):
                count += 1
                cur = cur.next
            #Point prev of node to cur
            node.prev = cur
            #Point the next node of node to the next node of cur
            node.next = cur.next
            #Point prev of cur's next node to node
            cur.next.prev = node
            #Point next of cur to node
            cur.next = node
    def remove(self, item):
        #Delete element
        if self.is_empty():
            return
        else:
            cur = self._head
            if cur.item == item:
                #If the element of the first node is the element to be deleted
                if cur.next == None:
                    #If the list has only one node
                    self._head = None
                else:
                    #Set prev of the second node to none
                    cur.next.prev = None
                    #Point the head to the second node
                    self._head = cur.next
                return
            while cur != None:
                if cur.item == item:
                    #Point the next of the previous node of cur to the next node of cur
                    cur.prev.next = cur.next
                    #Point prev of the next node of cur to the previous node of cur
                    cur.next.prev = cur.prev
                    break
                cur = cur.next

Queue (implemented in the form of linked list)

class Node(object):
    def __init__(self,elem,next=None):
        Self.elem = elem represents the corresponding element value
        Self. Next = next ා indicates the chain point of the next link
class Queue(object):
    def __init__(self):
        Self.head = none
        Self.rear = none ා the tail chain point is none
    def is_empty(self):
        Return self.head is none
    def enqueue(self, elem):
        P = node (elem) initializes a new point
        if self.is_empty():
            Self.head = P ා queue head is the new chain point
            Self.rear = P ා the end of the queue is a new chain point
        else:
            Self.rear.next = P ා the successor at the end of the queue is this new point
            Self. Rear = P ා then let the tail pointer of the queue point to this new point
    def dequeue(self):
        If self. Is "empty(): ා judge whether the queue is empty
            Print ('queue is empty '). If the queue is empty, exit the dequeue operation
        else:
            Result = self.head.elem the queue head element
            Self.head = self.head.next change the pointer position of the queue head
            Return result returns the queue header element
    def peek(self):
        If self. Is "empty(): ා judge whether the queue is empty
            If print ('not 'found') is empty, not 'found' will be returned
        else:
            Return self.head.elem returns the queue header element
    def print_queue(self):
        print("queue:")
        temp=self.head
        Myqueue = [] temporarily store queue data
        while temp is not None:
            myqueue.append(temp.elem)
            temp=temp.next
        print(myqueue)

Queue (implemented in array form)

class Queue():
    def __init__(self):
        Self.entries = [] ාindicates the parameters in the queue
        Self.length = 0 ා indicates the length of the queue
        Self. Front = 0 ා indicates the queue head position
    def enqueue(self, item):
        Self. Entries. Append (item) - add elements to the queue
        Self.length = self.length + 1 - queue length increased by 1
    def dequeue(self):
        Self.length = self.length - 1 - queue length reduced by 1
        Dequeued = self.entries [self. Front] ා the first element of the team is dequeued
        Self. Front - = 1 ා position of team leader reduced by 1
        Self.entries = self.entries [self.front:] the element of the queue is updated to the queue after retiring
        return dequeued
    def peek(self):
        Return self.entries [0] ා񖓿return the queue head element directly

Two fork tree

class Node(object):
    def __init__(self,item):
        Self. Item = item × indicates the corresponding element
        Self. Left = none = left node
        Self. Right = none indicates the right node
    def __str__(self):
        Return str (self. Item) prints the return value of STR when a node class is printed
class Tree(object):
    def __init__(self):
        Self. Root = node ('root ') -- the root node is defined as root which will never be deleted and used as a sentry.
    def add(self,item):
        node = Node(item)
        If self.root is none: ා if the binary tree is empty, the generated binary tree will be the new insertion point
            self.root = node
        else:
            Q = [self. Root] ා add the Q list to the root node of the binary tree
            while True:
                pop_node = q.pop(0)
                If pop ﹐ node.left is none: ﹐ if the left subtree is empty, add the point to the left subtree
                    pop_node.left = node
                    return
                Elif pop ﹣ node.right is none: if the right subtree is empty, add the point to the right subtree
                    pop_node.right = node
                    return
                else:
                    q.append(pop_node.left)
                    q.append(pop_node.right)
    def get_parent(self, item):
        if self.root.item == item:
            Return none - the root node has no parent node
        TMP = [self. Root] ා add the TMP list to the root node of the binary tree
        while tmp:
            pop_node = tmp.pop(0)
            If pop > node.left and pop > node.left.item = = item: the left subtree of a point is the point to be found
                Return pop > node > returns a point, which is the parent node of the search point
            If pop ﹣ node. Right and pop ﹣ node. Right. Item = = item: the right subtree of a point is the point to find
                Return pop > node > returns a point, which is the parent node of the search point
            If pop > node.left is not none: add TMP element
                tmp.append(pop_node.left)
            if pop_node.right is not None:
                tmp.append(pop_node.right)
        return None
    def delete(self, item):
        If self.root is none: if the root is empty, do nothing
            return False

        parent = self.get_parent(item)
        if parent:
            Del node = parent.left if parent.left.item = = item else parent.right
            if del_node.left is None:
                if parent.left.item == item:
                    parent.left = del_node.right
                else:
                    parent.right = del_node.right
                del del_node
                return True
            elif del_node.right is None:
                if parent.left.item == item:
                    parent.left = del_node.left
                else:
                    parent.right = del_node.left
                del del_node
                return True
            Else: left and right subtrees are not empty
                tmp_pre = del_node
                tmp_next = del_node.right
                if tmp_next.left is None:
                    Substitution
                    tmp_pre.right = tmp_next.right
                    tmp_next.left = del_node.left
                    tmp_next.right = del_node.right

                else:
                    While TMP? Next.left: let TMP point to the last leaf of the right subtree
                        tmp_pre = tmp_next
                        tmp_next = tmp_next.left
                    Substitution
                    tmp_pre.left = tmp_next.right
                    tmp_next.left = del_node.left
                    tmp_next.right = del_node.right
                if parent.left.item == item:
                    parent.left = tmp_next
                else:
                    parent.right = tmp_next
                del del_node
                return True
        else:
            return False

Dictionary tree

class TrieNode:
    def __init__(self):
        Self. Nodes = dict() -- build dictionary
        self.is_leaf = False
    def insert(self, word: str):  
        curr = self
        for char in word:
            if char not in curr.nodes:
                curr.nodes[char] = TrieNode()
            curr = curr.nodes[char]
        curr.is_leaf = True
    def insert_many(self, words: [str]):
        for word in words:
            self.insert(word)
    def search(self, word: str):
        curr = self
        for char in word:
            if char not in curr.nodes:
                return False
            curr = curr.nodes[char]
        return curr.is_leaf

heap

class heap(object):
    def __init__(self):
        #Initializing an empty heap, using arrays to store heap elements, saving storage
        self.data_list = []
    def get_parent_index(self,index):
        #Returns the subscript of the parent node
        if index == 0 or index > len(self.data_list) -1:
            return None
        else:
            return (index -1) >> 1
    def swap(self,index_a,index_b):
        #Swapping two elements in an array
        self.data_list[index_a],self.data_list[index_b] = self.data_list[index_b],self.data_list[index_a]
    def insert(self,data):
        #First put the elements at the end, and then heap them from the back to the front
        #In this case, if the insert element is larger than the parent node, it will be swapped until the last
        self.data_list.append(data)
        index = len(self.data_list) -1 
        parent = self.get_parent_index(index)
        #Loop until the element becomes the top of the heap, or less than the parent node (for a large top heap) 
        while parent is not None and self.data_list[parent] < self.data_list[index]:
            #Exchange operation
            self.swap(parent,index)
            index = parent
            parent = self.get_parent_index(parent)
    def removeMax(self):
        #Delete the top of heap element, then place the last element on the top of the heap, and heap it from top to bottom
        remove_data = self.data_list[0]
        self.data_list[0] = self.data_list[-1]
        del self.data_list[-1]

        Piled heap
        self.heapify(0)
        return remove_data
    def heapify(self,index):
        #Heap from top to bottom, starting from index (large top heap)
        total_index = len(self.data_list) -1
        while True:
            maxvalue_index = index
            if 2*index +1 <=  total_index and self.data_list[2*index +1] > self.data_list[maxvalue_index]:
                maxvalue_index = 2*index +1
            if 2*index +2 <=  total_index and self.data_list[2*index +2] > self.data_list[maxvalue_index]:
                maxvalue_index = 2*index +2
            if maxvalue_index == index:
                break
            self.swap(index,maxvalue_index)
            index = maxvalue_index

Recommended Today

Three common request methods: Ajax, Axios, fetch

JQuery is a fast and concise JavaScript framework, which is another excellent JavaScript code base (Uu or JavaScript framework) after prototype. The purpose of jQuery design is “write less, do more”, that is to advocate writing less code and doing more. It encapsulates common JavaScript function code, provides a simple JavaScript Design pattern, optimizes HTML […]