# 链接表基础结构
# item用于存储数据
# next指向下一个数据
class Node():
# 用tuple定义允许绑定的属性名称
__slots__=['_item','_next']
def __init__(self,item):
self._item=item
self._next=None
def getItem(self):
return self._item
def getNext(self):
return self._next
def setItem(self,newitem):
self._item=newitem
def setNext(self,newnext):
self._next=newnext
class SingleLinkedList():
def __init__(self):
self._head=None #初始化为空链表
def isEmpty(self):
return self._head==None
def size(self):
current=self._head
count=0
while current!=None:
count+=1
current=current.getNext()
return count
# 遍历链表
def travel(self):
temp_list = []
current=self._head
# print('遍历链表--开始')
while current!=None:
temp_list.append(current.getItem())
current=current.getNext()
print(temp_list)
# print('遍历链表--开始')
# 从头部添加数据
def add(self,item):
temp=Node(item)
temp.setNext(self._head)
self._head=temp
# 从尾巴添加数据
def append(self,item):
temp=Node(item)
if self.isEmpty():
self._head=temp #若为空表,将添加的元素设为第一个元素
else:
current=self._head
while current.getNext()!=None:
current=current.getNext() #遍历链表
current.setNext(temp) #此时current为链表最后的元素
# 检索元素是否在链表中
def search(self,item):
current=self._head
founditem=False
while current!=None and not founditem:
if current.getItem()==item:
founditem=True
else:
current=current.getNext()
return founditem
# 元素在链表中的位置
def index(self,item):
current=self._head
count=0
found=None
while current!=None and not found:
count+=1
if current.getItem()==item:
found=True
else:
current=current.getNext()
if found:
return count
else:
raise ValueError('%s is not in linkedlist'%item)
# 删除链表中的某项元素
def remove(self,item):
current=self._head
pre=None
while current!=None:
if current.getItem()==item:
if not pre:
self._head=current.getNext()
else:
pre.setNext(current.getNext())
break
else:
pre=current
current=current.getNext()
# 指定位置插入数据
def insert(self,pos,item):
if pos<=1:
self.add(item)
elif pos>self.size():
self.append(item)
else:
temp=Node(item)
count=1
pre=None
current=self._head
while count<pos:
count+=1
pre=current
current=current.getNext()
pre.setNext(temp)
temp.setNext(current)
if __name__=='__main__':
a = SingleLinkedList()
print(a.isEmpty())
for i in range(1,10):
a.append(i)
print(a.isEmpty())
print(a.size())
a.travel()
print(a.search(6))
print(a.index(5))
a.remove(4)
a.travel()
a.insert(4,100)
a.travel()
```
Python数据结构——链表
最新推荐文章于 2022-07-27 20:02:46 发布