Single Link List
class Node(object):
'''this is a node'''
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
'''this is a Singly Linked List'''
def __init__(self, node=None):
self.__head = node
def is_empty(self):
'''Judge whether it is empty'''
return self.__head == None
def length(self):
'''Length of linked list'''
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
'''Traversing chain list'''
cur = self.__head
while cur != None:
print(cur.elem, end=' ')
cur = cur.next
print('')
def add(self, item):
'''Add elements to linked list header'''
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item):
'''Add elements to the end of the linked list'''
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
'''Add elements to specified locations'''
if pos <= 0:
self.add(item)
elif pos > self.length():
self.append(item)
else:
node = Node(item)
pre = self.__head
count = 0
while count < pos:
count += 1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self, item):
'''Delete node'''
cur = self.__head
pre = None
while cur != None:
if cur.elem == item:
if pre == None:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def search(self, item):
'''Judge node existence'''
cur = self.__head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
def main():
s1 = SingleLinkList()
print(s1.is_empty())
print(s1.length())
s1.append(1)
s1.append(2)
s1.append(3)
s1.insert(2, 4)
s1.travel()
s1.add(6)
s1.travel()
print(s1.search(6))
print(s1.search(16))
s1.remove(6)
s1.remove(2)
s1.travel()
if __name__ == '__main__':
main()
---------------results of enforcement----------
True
0
1 2 3 4
6 1 2 3 4
True
False
1 3 4
-----------------------------------------------