The examples in this article describe how Python list operations work. Share to everyone for your reference.
The implementation method is as follows:
Copy the Code code 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 are 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 the 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 the 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 are 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
Hopefully this article will help you with Python programming.