class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getdata(self):
return self.data
def getnext(self):
return self.next
def setdata(self,newdata):
self.data = newdata
def setnext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
def isempty(self):
return self.head ==None
def add(self,item):
temp = Node(item)
temp.setnext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.getnext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
# print(current.getdata())
if current.getdata() == item:
found = True
else:
current = current.getnext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getdata() == item:
found = True
else:
previous = current
current = current.getnext()
if previous == None:
self.head = current.getnext()
else:
previous.setnext(current.getnext())
mylist = UnorderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
print(mylist.search(17))
mylist.remove(31)
print(mylist.size())
print(mylist.search(31))
2.有序列表
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getdata(self):
return self.data
def getnext(self):
return self.next
def setdata(self,newdata):
self.data = newdata
def setnext(self,newnext):
self.next = newnext
class OrderedList:
def __init__(self):
self.head = None
def isempty(self):
return self.head ==None
def size(self):
count = 0
current = self.head
while current != None:
count += 1
current = current.getnext()
return count
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getdata() == item:
found = True
else:
previous = current
current = current.getnext()
if previous == None:
self.head = current.getnext()
else:
previous.setnext(current.getnext())
def search(self,item):
current = self.head
found = False
while not found and current.getdata() < item and current != None:
if current.getdata() == item :
found = True
else:
current = current.getnext()
return found
def add(self,item):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getdata() > item:
stop = True
else:
previous = current
current = current.getnext()
temp = Node(item)
if previous == None:
temp.setnext(self.head)
self.head = temp
else:
temp.setnext(current)
previous.setnext(temp)
def vision(self):
current = self.head
list = []
while current != None:
list.append(current.getdata())
current = current.getnext()
return list
mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
print(mylist.vision())