class Node(object):
def __init__(self,item):
self.item=item
self.next=None
class SigleLinkList(object):
def __init__(self):
self.__head=None
def is_empty(self):
return self.__head==None
def length(self):
cur=self.__head
count=0
while cur!=None:
count+=1
cur=cur.next
return count
def trave(self):
cur=self.__head
while cur !=None:
print(cur.item,end="")
cur = cur.next
def add(self,item):
node = Node(item)
node.next = self.__head
self.__head = node
def append(self,item):
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):
if pos<0:
self.add(item)
elif pos>(self.length()-1):
self.append(item)
node=Node(item)
pre=self.__head
count=0
while count<(pos-1):
count+=1
pre=pre.next
node.next=pre.next
pre.next=node
def search(self,item):
cur=self.__head
while cur != None:
if cur.elem==item:
return True
else:
cur = cur.next
def remove(self,item):
cur = self.__head
pre=None
while cur!= None:
if cur.item==item:
if cur==self.__head:
self.__head=cur.next
else:
pre.next=cur.next
break
else:
pre=cur
cur=cur.next
if __name__=="__main__":
ll=SigleLinkList()
print(ll.is_empty())
print(ll.length())
print("-"*20)
ll.append(1)
print(ll.is_empty())
print(ll.length())
print("-" * 20)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.append(7)
ll.add(8)
ll.trave()
print(" ")
print("-" * 20)
ll.insert(5, 100)
ll.trave()
print(" ")
print("-" * 20)
ll.remove(100)
ll.trave()
True 0 -------------------- False 1 -------------------- 81234567? -------------------- 81234100567? -------------------- 81234567
|