class UnorderedList:
def __init__(self) -> None:
self.head=None
def add(self,item):
'''为链表添加节点,新增节点会在头部'''
temp=Node(item) #新的节点
temp.setNext(self.head) #将新节点的指向由None改成当前头节点的指向(类似于继承头节点的衣钵)
self.head=temp #将新节点设置为了头节点
def isEmpty(self):
'''判断链表是否为空'''
return self.head ==None
def length(self):
'''返回链表长度'''
count=0
current=self.head #初始化为头节点
while current!=None: #只要没到达末尾节点
count+=1
current=current.getNext() #指向下一个节点
return count
def search(self,item):
'''检查元素是否在链表中'''
cursor=self.head
while cursor!=None:
if cursor.getData()==item:
return True
cursor=cursor.getNext()
return False
def remove(self,item):
'''删除节点,成功返回True'''
cursor=self.head
previous=None #记录指针的前一个节点
while cursor!=None:
if cursor.getData()==item:
if previous==None:
self.head=None
return True
else:
previous.setNext(cursor.getNext())
return True
previous=cursor
cursor=cursor.getNext()
return False
def traverse(self):
'''遍历并返回一个所有值的列表,最左边为头节点'''
cursor=self.head
if cursor==None:
return []
result=[]
while cursor!=None:
result.append(cursor.getData())
cursor=cursor.getNext()
return result
def append(self,item):
'''在链表尾部添加节点,目标为让cursor移动到尾部'''
cursor=self.head
temp=Node(item) #临时存储新节点
if cursor==None:
self.head=temp
return
while cursor.getNext()!=None:
cursor=cursor.getNext()
cursor.setNext(temp)
def insert(self,index,item):
'''在index处插入节点'''
count=0
temp=Node(item)
previous=None
cursor=self.head
if cursor==None: #如果链表为空
if index==0:
self.head=temp
return
else:
return False
while cursor!=None:
if count==index:
if previous==None: #如果是第一个点
self.head=temp
temp.setNext(cursor)
return
else:
previous.setNext(temp)
temp.setNext(cursor)
return
count+=1
previous=cursor
cursor=cursor.getNext()
if count==index: #在尾部添加元素
previous.setNext(temp)
return
return False
def index(self,item):
'''查询节点的索引'''
count=0
cursor=self.head
while cursor!=None:
if cursor.getData()==item:
return count
else:
count+=1
cursor=cursor.getNext()
return False
def pop(self,index):
'''删除索引为index处的节点并弹出'''
cursor=self.head
previous=None #记录指针的前一个节点
count=0
if cursor==None:
return False
while cursor!=None:
if count==index:
if previous==None: #如果是第一个节点
self.head=cursor.getNext()
return cursor.getData()
else:
previous.setNext(cursor.getNext())
return cursor.getData()
else:
count+=1
previous=cursor
cursor=cursor.getNext()
return False