Python List Operation instance, python list instance
This article describes how to operate python lists. Share it with you for your reference.
The specific implementation method is as follows:
Copy codeThe Code is as follows: class Node:
"Single node in a data structure """
Def _ init _ (self, data ):
"Node constructor """
Self. _ data = data
Self. _ nextNode = None
Def _ str _ (self ):
"Node data representation """
Return str (self. _ data)
Class List:
"Linked list """
Def _ init _ (self ):
"List constructor """
Self. _ firstNode = None
Self. _ lastNode = None
Def _ str _ (self ):
"" List string representation """
If self. isEmpty ():
Return "empty"
CurrentNode = self. _ firstNode
Output = []
While currentNode is not None:
Output. append (str (currentNode. _ data ))
CurrentNode = currentNode. _ nextNode
Return "". join (output)
Def insertAtFront (self, value ):
"Insert node at front of list """
NewNode = Node (value)
If self. isEmpty (): # List is empty
Self. _ firstNode = self. _ lastNode = newNode
Else: # List is not empty
NewNode. _ nextNode = self. _ firstNode
Self. _ firstNode = newNode
Def insertAtBack (self, value ):
"Insert node at back of list """
NewNode = Node (value)
If self. isEmpty (): # List is empty
Self. _ firstNode = self. _ lastNode = newNode
Else: # List is not empty
Self. _ lastNode. _ nextNode = newNode
Self. _ lastNode = newNode
Def removeFromFront (self ):
"Delete node from front of list """
If self. isEmpty (): # raise exception on empty list
Raise IndexError, "remove from empty list"
TempNode = self. _ firstNode
If self. _ firstNode is self. _ lastNode: # one node in list
Self. _ firstNode = self. _ lastNode = None
Else:
Self. _ firstNode = self. _ firstNode. _ nextNode
Return tempNode
Def removeFromBack (self ):
"Delete node from back of list """
If self. isEmpty (): # raise exception on empty list
Raise IndexError, "remove from empty list"
TempNode = self. _ lastNode
If self. _ firstNode is self. _ lastNode: # one node in list
Self. _ firstNode = self. _ lastNode = None
Else:
CurrentNode = self. _ firstNode
# Locate second-to-last node
While currentNode. _ nextNode is not self. _ lastNode:
CurrentNode = currentNode. _ nextNode
CurrentNode. _ nextNode = None
Self. _ lastNode = currentNode
Return tempNode
Def isEmpty (self ):
"Returns true if List is empty """
Return self. _ firstNode is None
I hope this article will help you with Python programming.