def GetNo(self,e): #查找第一个为e的元素的序号 j=0 p=self.head.next while p is not None and p.data!=e: j+=1 #查找元素e p=p.next if p is None: return -1 #未找到时返回-1 else: return j #找到后返回其序号 def Insert(self, i, e): #在线性表中序号i位置插入元素e def Delete(self,i): #在线性表中删除序号i位置的元素 def display(self): #输出线性表 p=self.head.next while p is not None: print(p.data,end=' ') p=p.next; print() if __name__ == '__main__': L=LinkList() print() print(" 建立空单链表L") a=[1,2,3,4,5,6] print(" 1-6创建L") L.CreateListR(a) print(" L[长度=%d]: " %(L.getsize()),end=''),L.display() print(" 插入6-11") for i in range(6,11): L.Add(i) print(" L[长度=%d]: " %(L.getsize()),end=''),L.display() print(" 序号为2的元素=%d" %(L[2])) print(" 设置序号为2的元素为20") L[2]=20 print(" L[长度=%d]: " %(L.getsize()),end=''),L.display() x=6 print(" 第一个值为%d的元素序号=%d" %(x,L.GetNo(x))) n=L.getsize() for i in range(n-2): print(" 删除首元素") L.Delete(0) print(" L[长度=%d]: " %(L.getsize()),end=''),L.display()
时间: 2023-12-14 13:03:01 浏览: 101
python 中-self-标识符和self标识符.docx
这段代码的缺失部分应该是链表类 `LinkList` 的定义和实现,以下是可能的实现:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkList:
def __init__(self):
self.head = Node()
def CreateListR(self, a):
p = self.head
for i in a:
p.next = Node(i)
p = p.next
def Add(self, e):
p = self.head
while p.next is not None:
p = p.next
p.next = Node(e)
def getsize(self):
p = self.head.next
size = 0
while p is not None:
size += 1
p = p.next
return size
def __getitem__(self, index):
if index < 0 or index >= self.getsize():
raise IndexError("Index out of range")
p = self.head.next
for i in range(index):
p = p.next
return p.data
def __setitem__(self, index, value):
if index < 0 or index >= self.getsize():
raise IndexError("Index out of range")
p = self.head.next
for i in range(index):
p = p.next
p.data = value
def GetNo(self, e):
j = 0
p = self.head.next
while p is not None and p.data != e:
j += 1
p = p.next
if p is None:
return -1
else:
return j
def Insert(self, i, e):
if i < 0 or i > self.getsize():
raise IndexError("Index out of range")
p = self.head
for j in range(i):
p = p.next
p.next = Node(e, p.next)
def Delete(self, i):
if i < 0 or i >= self.getsize():
raise IndexError("Index out of range")
p = self.head
for j in range(i):
p = p.next
p.next = p.next.next
def display(self):
p = self.head.next
while p is not None:
print(p.data, end=' ')
p = p.next
print()
```
这个链表类包含了链表的基本操作,例如创建链表、插入元素、删除元素、修改元素、查找元素等。在测试代码中,我们首先创建一个空链表,然后通过 `CreateListR` 函数用列表 `[1,2,3,4,5,6]` 初始化链表。接着,在链表末尾添加了一些元素,输出链表长度和所有元素。然后,我们查找了第二个元素的值,并将其修改为 `20`,再次输出链表长度和所有元素。最后,我们删除了链表首部的元素,并输出删除后的链表长度和所有元素。
阅读全文