无序列表是一个没有特定顺序的列表项的集合,其特点为数据的排列不具有顺序性。无序表 List 的操作定义如下:
List():创建一个新的空列表。它不需要参数,并返回一个空列表。
add(item):向列表中添加一个新项。它需要 item 作为参数,并不返回任何内容(假定该 item 不在列表中)。
remove(item):从列表中删除该项。它需要 item 作为参数并修改列表(假设项存在于列表中)。
search(item):搜索列表中的项目。它需要 item 作为参数,并返回一个布尔值。
isEmpty():检查列表是否为空。它不需要参数,并返回布尔值。
size():返回列表中的项数。它不需要参数,并返回一个整数。
index(item):返回项在列表中的位置。它需要 item 作为参数并返回索引(假定该项在列表中)。
insert(pos,item):在位置 pos 处向列表中添加一个新项。它需要 item 作为参数并不返回任何内容。假设该项不在列表中,并且有足够的现有项使其有 pos 的位置。
pop():删除并返回列表中的最后一个项(假设该列表至少有一个项)。
pop(pos):删除并返回位置 pos 处的项。它需要 pos 作为参数并返回项(假定该项在列表中)。
# -*- coding: utf-8 -*-
class Node():
def __init__(self, init_data):
self.data = init_data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, new_data):
self.data = new_data
def setNext(self, new_next):
self.next = new_next
class UnorderedList():
#初始化列表
def __init__(self):
self.head = None
# 判断队列是否为空
def isEmpty(self):
return self.head == None
# 添加元素item
def add(self, item):
# ********** Begin ********** #
temp = Node(item)
#更改新节点的下一个引用以引用旧链表的第一个节点
temp.setNext(self.head)
#设置列表的头
self.head = temp
### 注意:
# 访问和赋值的顺序不能颠倒,因为head是链表节点唯一的外部引用
# 颠倒将导致所有原始节点丢失并且不能再被访问
# ********** End ********** #
# 返回列表长度
def size(self):
# ********** Begin ********** #
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
# ********** End ********** #
# 查询列表内是否存在item,查询结果:True or False
def search(self, item):
# ********** Begin ********** #
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
# ********** End ********** #
# 删除item元素
def remove(self, item):
# ********** Begin ********** #
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current #previous 必须先将一个节点移动到 current 的位置。此时,才可以移动current
current = current.getNext()
if previous == None: #如果要删除的项目恰好是链表中的第一个项,链表的 head 需要改变
self.head = current.getNext()
else:
previous.setNext(current.getNext())
# ********** End ********** #
# 打印列表内全部元素
def print_data(self):
# ********** Begin ********** #
current = self.head
while current is not None:
print(current.getData(), end = ' ')
current = current.getNext()
# ********** End ********** #
if __name__ == "__main__":
# 读取数据
line1 = list(map(int, input().split()))
line2 = int(input())
ulist = UnorderedList()
# 将数据依次压入
for i in line1:
ulist.add(i)
# 输出搜索结果
print(ulist.search(line2))
# 判定是否存在元素,若存在,则删除该元素
if ulist.search(line2):
ulist.remove(line2)
# 输出列表长度
print(ulist.size())
# 输出列表数据
ulist.print_data()