Python implementation of single-linked list

Source: Internet
Author: User

First of all, the linear table, linear table is one of the most basic, the simplest data structure, popular point is one-dimensional storage of data structure.

Linear tables are divided into sequential tables and linked tables:

    • Sequential representations refer to the data elements of a linear table, called sequential storage structures or sequential images of linear tables, sequentially, using a contiguous set of storage units.
    • Chained notation refers to the use of a set of arbitrary storage units to store data elements in a linear table, called a chain storage structure of linear tables. And he can be either continuous or discontinuous, and is constructed from a connection message to the successor node.
* Sequential table(This is not the focus, a brief introduction)

 Sequential tables store data elements in sequence with a contiguous storage unit, and it is convenient to find elements, but it is not as easy to add delete elements to them. Because add delete element to find that position first, because the order table inside is through the address of the continuous to make him a table, when the deletion of elements, to move the back of all the elements forward, to fill the address space above; adding elements is the same, you need to first move the elements behind that position back, To add elements to this address.

Take C as an example: a sequential table can be represented by an array, and each array created corresponds to a memory allocated to him. Of course, in addition to static allocation of space, can also be dynamically extended. Subsequent operations in this memory, generally need to move the array elements, the complexity will be very high.

In Python, there are two ways to express a sequential table:

      • One-piece construction
      • Split-type structure

The Oneness and separation here refers to the collection of elements in the table, and the information to be recorded for the correct operation, both in the same space or in a new space next to it.

The tuple and list in Python are implementation techniques that use sequential tables, but tuple is immutable and does not support internal operations. The list is a linear table with a variable number of elements, which supports operations such as adding deletes. The idea of list is actually the same as in the C language, just a few encapsulation of the function, that is, the properties of the list.

* Chain table

Linked list, as the name implies, adjacent nodes are connected through the chain, then what is the chain it. We know that in C there is a pointer to the pointer through the address to find his target. So, a node has not only his element, but also the address of his next element.

  So, pointers and addresses are needed here. What are the pointers in Python? Let's put this in the first place, first to understand the nature of the variable identifier in Python.

Look at this first, why is the ID of a and b the same? Let me ask you one more question: How do you implement the value of two variables in python?

1 a =2 b =3 a b = b,a

  Why would python be able to assign values like this? I'll draw another picture below.

 Is it understandable now that the variables themselves are stored as an address, exchanging their values is to change their point. So now know the meaning of the logo, our pointer field how to write, is not directly with the variable equals the next node ah. This seems to be not complicated, the next content is the same as the General list. I'm just saying this here to figure out how Python is creating links.

One, single linked list

Then the following is a class to implement a node, including data fields and link fields, the code implements a number of common functions, such as inserting, finding and so on. Today I'm mainly talking about how single-link lists are used in Python, because I haven't known them before. After learning, with their previous knowledge, it is convenient to use the linked list. The code behind is not too much to explain, you have to carefully ponder. What do not understand can leave a message, I will try to reply in detail.

1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #@Date: 2018-06-12 11:23:214 #@Author: yudanqu ([email protected])5 #@Link: https://www.cnblogs.com/yudanqu/6 #@Version: $Id $7 8 9 classNode (object):Ten     """node""" One  A     def __init__(self, elem): -Self.elem =Elem -Self.next = None#initial setup Next node is empty the  - " " - The class of a node is defined above, and some of the structure of Python can be used directly. For example, through tuples (Elem, None) - " " +  -  + #Create a single-linked list below and implement its proper functionality A  at  - classSinglelinklist (object): -     """single linked list""" -  -     def __init__(Self, Node=none):#use a default parameter that is received when the header node is passed in, and the default header node is empty when no incoming -Self.__head=node in  -     defIs_empty (self): to         " "whether the linked list is empty" " +         returnSelf.__head==None -  the     defLength (self): *         " "Linked list length" " $         #cur cursor, used to move traversed nodesPanax Notoginsengcur = self.__head -         #Count Record Quantity theCount =0 +          whileCur! =None: ACount + = 1 theCur =Cur.next +         returnCount -  $     defTravel (self): $         " "traverse the entire list" " -cur = self.__head -          whileCur! =None: the             Print(Cur.elem, end=' ') -Cur =Cur.nextWuyi         Print("\ n") the  -     defAdd (Self, item): Wu         " "adding elements to the list header" " -node =Node (item) AboutNode.next = self.__head $Self.__head=node -  -     defAppend (self, item): -         " "adding elements to the tail of a list" " Anode =Node (item) +         #because of the special case, there is no next when the list is empty, so make a judgment in front of it . the         ifself.is_empty (): -Self.__head=node $         Else: thecur = self.__head the              whileCur.next! =None: theCur =Cur.next theCur.next =node -  in     defInsert (self, POS, item): the         " "add element at specified location" " the         ifPOS <=0: About                 #if the POS position is in 0 or before, then it is used as the head interpolation method . the Self.add (item) the         elifpos > Self.length ()-1: the             #if the POS position is longer than the original chain, then it is done as a tail interpolation method . + self.append (item) -         Else: theper = self.__headBayiCount =0 the              whileCount < Pos-1: theCount + = 1 -per =Per.next -             #when the loop exits, the pre points to the pos-1 position thenode =Node (item) theNode.next =Per.next thePer.next =node the  -     defRemove (self, item): the         " "Delete a node" " thecur = self.__head thePre =None94          whileCur! =None: the             ifCur.elem = =Item: the                 #first, determine if the node is a head junction. the                 ifCur = = self.__head:98Self.__head=Cur.next About                 Else: -Pre.next =Cur.next101                  Break102             Else:103Pre =cur104Cur =Cur.next the 106     defSearch (self, item):107         " "find whether a node exists" "108cur = self.__head109          while  notcur: the             ifCur.elem = =Item:111                 returnTrue the             Else:113Cur =Cur.next the         returnFalse the  the 117 if __name__=="__main__":118 119         #Node = node (100) # First create a node to pass in - 121LL =singlelinklist ()122     Print(Ll.is_empty ())123     Print(Ll.length ())124  theLl.append (3)126Ll.add (999)127Ll.insert (-3, 110) -Ll.insert (99, 111)129     Print(Ll.is_empty ()) the     Print(Ll.length ())131 Ll.travel () theLl.remove (111)133Ll.travel ()
Second, one-way circular linked list and two-way linked list

Associated with a single-linked list, there is also a one-way circular link list and a doubly linked list:

  One-way loop linked list: On the basis of a single linked list, and one more from the tail node point to the first node of the link, the first node refers to the list of the first data nodes, and head nodes refers to the first data node of the thing, there is only a link domain, rather than the actual storage of the content of the linked list node. It should be noted that in the circular list, some of the functions of the creation is not the same as a single-linked list, such as the sentence empty, full, it is a circular how to judge it? These can be modified in the implementation of the single linked list given above, you can try it.

  Doubly linked list: This new feature is bidirectional compared to a single linked list. It can be passed back to the rear, or it can be passed from the back to the front, the front and back of which we define ourselves, that is positive from one end to the other, and vice versa. The implementation of this doubly linked list is basically the same as a single-linked list. A one-way list is a link field that is added to the data field to point to the next node. Then again, the doubly linked list adds a link to the previous node. When you create a linked list at this point, you have to set up the links between each node and the predecessor nodes and the subsequent nodes.

Two-way linked list of the insertion and deletion and so on, should pay attention to, do not store the address information lost, carefully consider the direction of both sides, first who link up, and then link who.

Today, I just want to talk about the front of a little bit of content, write, the back feeling had to say, but also did not write more complete. Everybody pick up something useful to see.

Python implementation of single-linked list

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.