2019.9.17-07- singly linked list to find and delete elements of the code (+ before the full version)

# coding:utf-8


class Node(object):
"""節點0"""
def __init__(self, elem):
self.elem = elem
self.next = None

# node = None(100)
class SingleLinkList(object):
"""單鏈表"""
def __init__(self, node=None):
self.__head = node

def is_empty(self):
"""鏈表是否爲空"""
return self.__head == None

length DEF (Self):
"" "chain length" ""
# CUR Park travel for traversing the mobile node
CUR = Self .__ head
# record number COUNT
COUNT = 0
the while CUR = None:!
COUNT + =. 1
CUR = CUR .next
return COUNT

def travel(self):
"""遍歷整個鏈表"""
cur = self.__head
while cur != None:
print(cur.elem, end=" ")
cur = cur.next
print("")


the Add DEF (Self, Item):
"" "additive element list header, the first interpolation method" ""
Node = the Node (Item)
node.next head .__ = Self
Self .__ head Node =

the append DEF (Self, Item):
"" "additive element list tail, tail interpolation" ""
Node = the Node (Item)
IF self.is_empty ():
Self .__ = Node head
the else:
CUR = Self .__ head
the while CUR = None .next:!
CUR = cur.next
cur.next the Node =

INSERT DEF (Self, POS, Item):
"" "additive element specified location
: param pos from 0
" ""
IF POS <= 0:
self.add (Item)
elif POS> (self.length () -. 1) :
self.append (Item)
the else:
pre = Self .__ head
COUNT = 0
the while COUNT <(pos-1):
COUNT = +. 1
pre = pre.next
# when the loop exits, pre pos-1 points to the location
node = Node (Item)
node.next = pre.next
pre.next Node =

Remove DEF (Self, Item):
"" "Delete Node" ""
CUR head .__ = Self
pre = None
the while CUR = None:!
IF cur.elem == Item:
# determines whether the first node is the head node
# Head node
IF == Self .__ head CUR:
Self head .__ = cur.next
the else:
pre.next = cur.next
BREAK
the else:
pre = CUR
CUR = cur.next

def search(self, item):
"""查找節點是否存在"""
cur = self.__head
while cur != None:
if cur.elem == item:
return True
else:
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.add(8)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
# 8 1 2 3 4 5 6
ll.insert(-1, 9) # 9 8 123456
ll.travel()
ll.insert(3, 100) # 9 8 1 100 2 3456
ll.travel()
ll.insert(10, 200) # 9 8 1 100 23456 200
ll.travel()
ll.remove(100)
ll.travel()
ll.remove(9)
ll.travel()
ll.remove(200)
ll.travel()

 

 

 

 

 

 

 

 

 

 

The final results show

 

Guess you like

Origin www.cnblogs.com/lishuide/p/11531217.html