Data structures and algorithms - Data structure - linear structure - the sequence list tables and hash tables

#######################################################

"""
# Linear table is one of the most basic data structure, the actual procedure is widely used, it is often used as a basis more complex data structures.

# The actual linear form of storage, is divided into two models to achieve:
# Sequence table,
# List,
# The following were studied,


"""

 

#######################################################

"""

Study # sequence table
# Basic form of the sequence table, the data storage element itself continuously,

# The first case:
# If the storage elements in the sequence table are a fixed size, only one space,
# Second case,
# But the size of each element does not store all fixed, such as a list, the numbers may be stored, but there are strings, and the like,
# Each value is can be placed in another storage block, and the address of each memory block in order to save up table,
# When this value, you need to find the address, and then go find the address storage block, find specific content,

# Order form of realization,
# 8 elements such as storage, the storage operating system to apply to one-off,
# So a sequence table, in addition to the specific storage contents to be saved, but also a header,
# Header requires two pieces of information that a capacity is how much is the maximum storage information, and the other is now stored content, which is now stored in a number of elements,
# How to store and header information together?
# One is stored together, this is called integrated storage,
# One is stored separately, this is called separation of storage, plus a store information in the header when the content is stored in the address, which is a three meter, capacity, address the current number of storage, storage information,


# Integrated storage and separate storage, which is good?
# Reads: one type of memory, skip the meter can read, separate storage is one more step, to obtain the start address information header, and then get specific information to the address,
# Extended Data:
# Integral storage capacity is fixed, if the multi-bank data, must reapply empty space, and then transfer the data over, but also move over the header,
# Separate storage, the header does not need to be changed, only the address to the new address on,
# So for considering the dynamic data changes, or more uses separate memory,

# How to expand the application space of time estimated it?
# For example, the original space can only store four elements, in order to store the 5th element, I need to re-apply for space,
# First embodiment, the fixed applications, such as to apply each space 10, 14 is, space-saving, but the frequent operation,
# The second way, doubling the way, beginning 4, the next time is doubled, that is, eight, this sacrifice some space, but time will be more efficient, which is the space for time,

# Drawbacks of the order table is also very obvious, is the time to expand the data, you need to re-apply for space, then is there a structure, one more data, they add up, rather than re-apply for space?
That is the list of #


"""

 

 #######################################################

"""
Study # linked list
# A list, you need to store three elements 200,300,400
# No order table, which is restricted, the use of each element to increase a space application, then open a new space behind each element, an element used to point to another,
# This link layers on it, this is the list,

How to implement a linked list #: 
# list each element is an object, each object is a node, the data comprising a next pointer field of the node key and a point. By various interconnections between nodes, the final series into a list # Each element holds two content, accurate in terms of the elements can not be called, but called nodes, # A message is called a data area, # Is a link address of the next element, which is called a link area, the end point node that points to an empty area, # Singly linked list, # Head node is the first node, the second node is tail node, # Python exchange operating variables, # a=10 # b=10 # A, b = b, a # that is exchanged, only in Python there, no other language, # Why can achieve this effect, what essentially? # A is a space 10 is a space, the space A space 10 points, # So this exchange is the point of change, so it is not really assignment # So remember, Python variables are not saved in the content, but to maintain the address stored in the address pointed to where the information is specific, # So a just equal numbers, strings, lists, etc., it is because of this variable is a point, which is the difference between Python and other languages,
"""

 

 

 #######################################################

"""

One-way linked list,
logic:
1. Because each node of the list, you need to save data and links to our own definition of a data type called a node type to hold two pieces of information,
2. Define a single chain class, there is no initial node, empty head 
3, several methods to achieve
determines whether the air,
returns the length of the list
traversal
header is added,
the tail was added
intermediate add
delete nodes,
lookup,
"""

 

################## python one-way linked list #######################

class SingleNode(object):
    # There are two elements
    def __init__(self,elem):
        = self.elem element
        self.next = None # For a start, there is only one element, I do not know what the next element is,
    

# Step 1: Create a new list
# Sll = SingleLinkList (), which is empty inside, without any node, point head ---- None,
# Step Two: Now the list has to save an integer value 100, it is necessary to construct a node,
# Node = SingleNode (100) # It contains two values ​​is 100, none, then the head of the list is not none, is the first node,
class SingleLinkList(object): """Single list"""
    def __init__(self,node=None): self .__ head = None # private property set to null, this means that there is no node in the list, the first
 DEF is_empty (Self): "" "determine whether the list is empty" "" return self .__ head == None # as long as the list is none the head of the list is empty, # how to achieve this length, because the list is the head ---- 100, next --- 20, next --- 300, next --- none # so to traverse the linked list, if none is next on coming to an end, DEF length (Self): "" "chain length" "" # cur cursor for the mobile node traversal, cur = self .__ head # count is used to count, cOUNT = 0 point to the end node # None, when the tail cur = not reach the while! None: cOUNT. 1 + = cur = cur.next the cur # after the move a node, this one is critical, return COUNT DEF Travel (Self): "" "traverse the list" "" CUR = Self .__ head the while CUR =! None: Print (cur.elem, End = "" ) CUR = in the case of a head logic cur.next # # the first step in the insertion of data, the next new element points to the first node, a second step #, the head point to the new element # can handle this logic is the empty list, DEF add (self, item): " " " head Add element" ""# Create a saved value of the item node node =SingleNode (item) # the next link field pointing to the head node of the new node, i.e. the location pointed _head node.next = self .__ head # This is the original __head head node # _head head of the list points to the new node .__ head = Self the node DEF the append (Self, Item): "" "tail add elements" "" the node = SingleNode (Item) # first determine whether the list is empty, if empty list, then _head point to the new node iF Self. is_empty (): Self .__ head = the node # if not empty, then find the tail end of the next node point to the new node the else : CUR = Self .__ head the while cur.next =! None: this is the # CUR = cur.next an attribute, a node holds the class object, traversing through a pass, put the cur become the tail node, cur.next = node # this is the pointer to the tail node a node coordinate inserted through # implementation logic # inset (2,300) # the first step, so that the new node, pointing to the original node is the node 2, # second step, so that the left is node 1, point to the new node, because the # pass over the coordinates of the user use, so the need to control, # 1, if it is passed 0 # 2, If it is larger than the length of the incoming DEF INSERT (Self, pos, Item): "" "designated location additive element" "" # pos before the specified position if the first element, the insertion head portion is performed if pos < = 0: Self.): Self.append (item) # find the specified location the else : Node = SingleNode (Item) COUNT = 0 # pre used to point to specify a position of the previous position pos pos-1, the initial head node starts to move to the specified position pre = self the while COUNT head .__ <(pos -. 1 ): = COUNT +. 1 pre = pre.next if pos # 2, then this is the original coordinates are pre.next node 2, node.next = pre.next # new node node before a next node point next insertion position of the node pre.next = node # position the insertion point to a new node # incoming data, need to delete specific data, implement the logic #, # needs to delete a node a pointer to the next node in the node, so that the chain link up with two cursors # to solve this problem, # 1, cur pointer on head # 2, pre cursor points cur, # 3, cur point DEF cur.next Remove ( self, item): "" "delete node" "" CUR = Self .__ head pre = None CUR = the while!None: if cur.elem == item: # find elements if cur == self .__ head to be removed: # node to be removed, if found, is just the first node is the first node to determine how? : Cur == self .__ head self .__ head = cur.next # is to head directly point to the deleted node next else: # pre.next = cur.next # after the former location of the next point to delete a node position of a deleted node, even if the wording only one node can be realized, the else BREAK : # nodes continue to move the chain, which is two to two cursors are moved backward, pre = CUR CUR = cur.next implementing logic # # still need to traverse the list, the determination node data and user data are looking for, equality, equal if it returns true, otherwise false, DEF Search (Self, Item): "" "list to find out if there is a node, and returns True or False "" " CUR = Self .__ head the while CUR =! None: IF cur.elem == Item: return True CUR = cur.next return False IF __name__ ==" __main__ " : LL = SingleLinkList () Print (ll.is_empty ()) Print (ll.length ()) ll.append (. 1 ) Print(ll.is_empty()) print(ll.length()) ll.append(2) ll.append(3) ll.append(4) ll.append(5) ll.add(9) ll.insert(-1,200) ll.insert(1,300) ll.insert(11,400) ll.remove(400) ll.travel()

 

##################################################

"""

# Doubly linked list
# Each node needs to save the contents of the three, a node address, the data from this node, the address of the next node,
# This makes it a successor and predecessor node node,
# Predecessor node for the first node is empty, the tail node to the next node is empty,
 

"""

 

################## python achieve a doubly linked list #######################

class Node(object):
    "" "Doubly linked list node" ""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

 class DLinkList (Object): "" "doubly linked" "" DEF the __init__ (Self): Self .__ head = None DEF is_empty (Self): # and a single list is the same, "" "determines the list is empty." "" return self .__ head is None # self .__ head == None you can use the double equal sign, but pep8 recommended is, def length (self): # and a single list is the same, "" "the resulting list length" "" Self head .__ = CUR COUNT = 0 the while CUR =! None: = COUNT +. 1 CUR = cur.next return COUNT DEF Travel (Self): # is the same and single list, "" "traversal chain" "" CUR = Self CUR = the while head .__! None: Print (cur.item) CUR = cur.next # single list and this is not the same, you add a node # # the first step in the head, under the next point to the new node of a step # node, the new node is equal to the third step # head, the original head PREV node to the new node, DEF the Add (Self, Item): """Header insertion element" "" Node = the Node (Item) IFself.is_empty (): # If the list is empty, the point _head self._head = Node Node the else : node.next self .__ head # = empty list when a self .__ head or none, so the next is equal to none, self .__ head = node # Keep your head node is equal to this node, node.next.prev = node # node.next this is the original head node, he points to the new node # prev single list and this is not the same, the first step # , next original tail node to the new node, the second step #, PREV new node, the end point to the original node, DEF the append (Self, Item): "" "trailing insert elements" "" node = the Node (Item) IF self.is_empty (): # If the list is empty, the head __head point .__ = Self Node Node the else : # moved to the tail of the linked list head .__ the while Self = CUR cur.next =! None: CUR = CUR # .next this step is moved to the tail node node # tail cur = cur.next next point node node # prev points to the node cur node.prev =the insertion node # prev cur, single chain and is not the same, the first step #, the next new node pointing to the original position, node.next = cur # the second step, the new node to the original node location on a cur .prev, node.prev = cur.prev # third step, the original on a next node point to the new location of the node, node, prev.next = node # fourth step, prev original position to the new node, cur .prev = node # code is not unique, but to clear rationale, this surface may be questions, drawing can be appreciated, DEF INSERT (Self, POS, Item): "" "add a node at the specified position" "" if pos < = 0: self.add (Item) elif POS> (self.length () -. 1 ): self.append (Item) the else : CUR = self._head COUNT = 0 # moved to a position before the specified position while count < pos: COUNT + 1 = CUR = cur.next # exit the loop when, cur point position pos node =Node (item) node.next = cur # a first step, next new node to the original node node.prev = cur.prev # position a second step, prev new node to the node one node to the original position. prev.next = node # third step, a node on the next original position to the new node cur.prev = node # fourth step, the original point position prev new logical node # single list and not the same, # the first step: let the deletion of nodes on a node next, pointing to delete a node to the next node, cur.prev.next = cur.next # second step, let's prev next delete a node, the node point to delete a node, cur.next.prev = cur.prev # If the node is the first, # the first step: let head equal to a second stage of the current node node #: prev next node to the current node becomes none, # only one node when # directly head equal to the next current node as the current node's next is none, DEF the Remove (Self, Item): "" "delete element" "" ! CUR = Self .__ head the while CUR = none: IF cur.item == Item: IF == Self .__ head CUR : Self .__ HEA = D cur.next IF cur.next: # This is the time devoted to a single node, since there is only one node, cur.next.prev which is of no value, cur.next.prev = None the else : cur.prev. next = cur.next # of the next previous node after the cur point cur if a nodecur.next: cur.next.prev = cur.prev # after the cur prev points to a node in a node before the break else cur : cur = cur.next DEF Search (Self, Item): "" "Find elements are presence of "" " CUR = Self .__ head the while CUR =! None: IF cur.item == Item: return True CUR = cur.next return False IF the __name__ ==" __main__ " : LL = DLinkList () ll.add (. 1 ) ll.add (2 ) ll.append (. 3 ) ll.insert (2,. 4 ) ll.insert (. 4,. 5 ) ll.insert (0,. 6 ) ll.travel () ll.remove (. 1 ) LL. travel ()

 

################## python one-way circular list #######################

#-Way circular list,
# The only difference is that tail and unidirectional linked list node points to the next node of the head,


class Node(object):
    """节点"""
    def __init__(self, item):
        self.item = item
        self.next = None


class SinCycLinkedlist(object): "" "One-way circular list" "" __init __ DEF (Self, the Node = None): Self .__ head = None IF the Node: node.next the Node # = only one element should point to themselves, def is_empty (self): # and a single list as "" "determine whether the list blank "" "Self return .__ head == None DEF length (Self):" "" the resulting list length "" "# If the list is empty, return length IF 0 self.is_empty (): return 0. 1 COUNT = CUR ! = self .__ head while cur.next = self .__ head: # tail determination conditions have changed, next if a node is a head node, which is the tail node, COUNT + =. 1 CUR = cur.next return COUNT DEF Travel (Self): "" "traversal chain" "" IF self.is_empty (): return CUR = Self = Self cur.next the while head .__ .__ head! : Print (cur.item) CUR =cur.next # exit the loop, cur point to the end node, the end node elements but not printed, print (cur.item) # for an empty node, where a node is able to meet, # # logical first step, next new node to the head node # original second step, the junction point to the new head node # third step, the end of the next node point to the first node, if # is an empty list, DEF the Add (Self , item): "" "Add node head" "" node = the node (Item) IF self.is_empty (): = head .__ Self node Self .__ = node.next head the else : node.next head # = Add Self .__ the node point __head cur = self .__ head # this is to set the cursor cur.next = Self .__ head the while! : CUR = cur.next # constantly moving back cur.next = node # exit the loop, cur is pointing to the tail node, the tail node to the next node self .__ head = node # head junction point to the new node # # logical first step, the next new node to the head, # a second step, the original end node next point points to the new node, DEF the append (Self, Item): "" "Add node tail" "" node = the node (Item) IF SEL f.is_empty (): = head .__ Self Node node.next = Self.: Move list # = Self .__ tail head the while CUR = Self cur.next .__ head! : CUR = cur.next cur.next the tail node = node # point node node.next = self .__ head # head node to node points single list and __head # logic is the same, DEF INSERT (Self, POS, Item): "" "Add specified location node" "" IF POS <= 0: self.add (Item) elif POS> (Self. length () -. 1 ): self.append (Item) the else : Node = the Node (Item) CUR = Self .__ head COUNT = 0 # moved to a position before the specified position COUNT the while <(-POS. 1 ): = COUNT + . 1 CUR = cur.next node.next = cur.next cur.next = node # # logic if the first node is deleted, the first step #, head directed deletion node # Step next node, the end node the next point to the new head, # if not the first node, # and a single chain, as directly to the delete of a node of the next point to the next node of the deletion node, DEF remove (Self, Item): "" "delete a node "" "# If the list is empty, then direct return IF self.is_empty (): returnSelf head .__ = CUR pre = ! = None Self cur.next the while head .__ : IF cur.item == Item: Self == IF cur.next head .__: # This is the case of the head node, if the first node # point still need to iterate again, RCUR Self .__ head the while rcur.next = = Self .__ head! : RCUR = rcur.next Self .__ head = cur.next rcur.next = Self .__ head the else: # is not the first case of pre nodes = .next cur.next return the else : pre = CUR CUR = cur.next # exit the loop, cur point to the end node, IF cur.item == Item: IF CUR == Self .__ head : head Self .__ = None the else : = pre.next cur.next # single list and not the same as DEF Search (Self, Item): "" "to find whether there is a node" "" iF self.is_empty (): return False Self CUR = .__ head the while cur.next! = self .__ head: # this traversing the node missing tails, tail node to handle it alone, if cur.item ==Item: return True the else : CUR = cur.next # exit the loop, cur point tail node, if cur.item == item: # tail node is determined, return True return False # so you will find the process, the code not a problem, are the most basic, the key is to make logical reason clearly, # you can also be expanded to a doubly linked list, is to become a two-way circular linked list, IF __name__ == "__main__" : LL = SinCycLinkedlist () ll.add (. 1 ) ll.add (2 ) ll.append (. 3 ) ll.insert (2,. 4 ) ll.insert (. 4,. 5 ) ll.insert (0,. 6 ) ll.travel () ll.remove (. 1 ) ll.travel ()

 

##############################################

"""

Hash table
Hash table (also called a hash table), a memory structure of a linear form. A hash table from the sequence table (array) and composed of a hash function. Hash function h (k) as an argument to k, returns the index storage elements.

Applying a hash table in Python
a, dictionaries and collections are achieved by a hash table
b, in Python dictionary:
a = { 'name': 'Alex', 'age': 18, 'gender': 'Man'}, use a hash table to store the dictionary, the dictionary by the hash function for the key mapping index.
c, the next small number of cases, almost does not occur hash collision in a dictionary key, this time to find an element of time complexity is O (1).
 
"""

 

 

##############################################

 

##############################################

 

 

##############################################

 

 

##############################################

Guess you like

Origin www.cnblogs.com/andy0816/p/12348242.html