[Note]PYTHON data structure of linear table: LinkedList list, stack stack, queue queues

Source: Internet
Author: User

A linear table of Python data structures
python contains many advanced data structures, List,dict,tuple,string,set, etc., For example, when using a list to implement a queue, the queue operation append () time complexity can be considered O (1), but the time complexity of the outbound operation pop (0) is O (n). If you want to use Python to learn the data structure, I think it is better to implement the basic data structure.
1. Linked listin this case, I want to use the form of chained storage similar to the C language, with the help of class to form unordered linked lists and ordered linked lists, respectively. let's look at the definition of the linked list node first:
Class ListNode (object):    def __init__ (self, data):        self.data = data        Self.next = None    def getData (self):        return self.data    def setData (self, newdata):        self.data = NewData    def getNext (self):        return Self.next    def setnext (self, nextnode):        self.next = NextNode
Use linked list nodes to form unordered list classes:
Class Unorderedlist (object): Def __init__ (self): Self.head = None def gethead (self): return Self.head def isEmpty (self): return Self.head was None def add (self, item): node = ListNode (item) Node.nex t = self.head self.head = node # The head is the most recently added node def size (self): current = Sel        F.head count = 0 While current was not none:count + = 1 current = Current.getnext () Return Count Def search (self, item): current = Self.head found = False and current was not No NE and not found:if current.getdata () = = Item:found = True else:cur Rent = Current.getnext () return found def append (self, item): node = ListNode (item) if self.isempt Y (): self.head = node else:current = self.head while Current.getnext () are not Non E:current = Current.getnext () current.setnext (node) def remove (self, item): current = Self.head Previo US = None found = False while not found:if current.getdata () = = Item:found = Tru E else:previous = Current current = Current.getnext () If previous is None : Self.head = Current.getnext () else:previous.setNext (Current.getnext ())
In the list above, each add element is added directly to the list header, the time complexity of Add () is O (1), and the Append () operation at the end of the queue, its time complexity is O (n). Is there a linked list of O (1) for the time complexity of adding operations, and of course there are:
Class Unorderedlist (object): Def __init__ (self): Self.head = None Self.tail = None def gethead (self): Return Self.head def isEmpty (self): return self.head is None and Self.tail was none def add (self, item) : node = ListNode (item) if Self.isempty (): Self.head = self.tail = Node Else:n Ode.next = Self.head self.head = node # The head is the most recently added node def size (self): CU Rrent = Self.head Count = 0 While current is not none:count + = 1 current = Current.ge Tnext () return Count Def search (self, item): current = Self.head found = False while Curren                T is not None and not found:if current.getdata () = = Item:found = True Else: Current = Current.getnext () return found def append (self, item): node = ListNode (item) SEL    F.tail.setnext (node)    Self.tail = node def remove (self, item): current = Self.head previous = None found = False                While not found:if current.getdata () = = Item:found = True Else: Previous = Current current = Current.getnext () if Current.getnext () is None:self.tail = Previous if previous is None:self.head = Current.getnext () else:previous.setNext (cur Rent.getnext ())
Add an attribute to the unordered list class, referencing the node at the end of the list. This change should be made in the Add and remove operations as well.Let's look at the ordered list below. The ordered list looks for the appropriate node position when inserting the node.
Class Orderedlist (object): Def __init__ (self): Self.head = None def isEmpty (self): return self.head is None def search (self, item): Stop = false found = False current = Self.head and current Is isn't None found and not stop:if current.getdata () > item:stop = True E        Lif current.getdata () = = Item:found = True else:current = Current.getnext () Return found Def add (self, item): previous = None current = Self.head stop = False whil                E current was not None and not stop:if current.getdata () >item:stop = True Else: Previous = Current current = Current.getnext () node = ListNode (item) if Previo            US is None:node.getNext (current) Self.head = node Else:previous.setNext (node) Node.setnext (CUrrent) 
2. Stack stackfor Stacks, Python's built-in list already satisfies the stack's requirements. The stack operation is append (), and the stack operation is pop (). They have a time complexity of O (1).
Class Stack (object):    def __init__ (self):        self._items = []    def is_empty (self):        return Self._items = = []    def push (self, item):        self._items.append (item)    def pops (self):        return Self._items.pop ()    def Peek (self):        return self._items[-1]
Of course, we can also implement the link stack, similar to the implementation of the list.
class Stacknode (object): "" "DocString for Stacknode" "" Def __init__ (self, value): Self.value = value Self.next = Noneclass Stack (object): "" "DocString for Stack" "" Def __init__ (self, top =none): Self.top = Top def get_top (self): return self.top def is_empty (self): return self.t        OP is None def push (self, Val): If Self.is_empty (): Self.top = Stacknode (val) return     Else:node = Stacknode (val) node.next = Self.top.next self.top = node return        def pop (self): if Self.is_empty (): Print ("Stack is empty, cannot pop anymore.\n") return node = self.top Self.top = self.top.next return node 
3. Queued QueueIf the queue is implemented using a linked list, the questions mentioned at the beginning of the article appear. so the queue can be implemented with a linked list.
Class Queuenode (object):    def __init__ (self, value):        self.value = value        self.next = Noneclass Queue (object) :    def __init__ (self):        Self.front = none        Self.rear = None    def is_empty (self):        return Self.front is None and Self.rear are none    def enqueue (self, num):        node = queuenode (num)        if Self.is_empty ():            Self.front = node            self.rear = node        else:            self.rear.next = node            self.rear = node    def dequeue ( Self):        if Self.front is self.rear:            node = self.front            Self.front = none            self.rear = None            return Node.value        Else:            node = self.front            Self.front = node.next            return node.value
There are deque modules in the Python library, such as collections and queue.the Deque module, as its name implies, can do double-ended queues. So, the Deque module can also do queues, and stacks. dq = deque ([1,2,3,4,5,6,7,8,9])Dq.pop () # Pop 9dq.popleft () #pop 1Dq.apend (9) # Append 9dq.appendleft (1) #insert 1 in index 0in multi-threaded, multi-process programming, the queue class of the queue module is often used. In fact: Suppose q = queue.queue () then Q.queue is a deque. We'll talk about this later.







[Note]PYTHON data structure of linear table: LinkedList list, stack stack, queue queues

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.