Python中的链表-追加、索引、插入和弹出函数。不确定是否存在代码/错误
这个任务要求我们为无序链表实现append、insert、index和pop方法。 (到目前为止我所拥有的)Python中的链表-追加、索引、插入和弹出函数。不确定是否存在代码/错误,python,insert,indexing,linked-list,Python,Insert,Indexing,Linked List,这个任务要求我们为无序链表实现append、insert、index和pop方法。 (到目前为止我所拥有的) def main(): 类节点: 定义初始化(自身,数据): self.data=数据 self.next_节点=无 类链接列表: 定义初始化(自): self.head=无 self.tail=None def追加节点(自身、数据): 新节点=节点(数据) 如果self.head==无: self.head=新节点 如果是self.tail!=无: self.tail.next=新节点
def main():
类节点:
定义初始化(自身,数据):
self.data=数据
self.next_节点=无
类链接列表:
定义初始化(自):
self.head=无
self.tail=None
def追加节点(自身、数据):
新节点=节点(数据)
如果self.head==无:
self.head=新节点
如果是self.tail!=无:
self.tail.next=新节点
self.tail=新节点
def打印列表(自我):
node=self.head
while节点!=无:
打印(节点数据)
node=node.next
def PopNode(自身,索引):
prev=无
node=self.head
i=0
而(节点!=无)和(i<索引):
prev=节点
node=node.next
i+=1
如果prev==无:
self.head=node.next
其他:
prev.next=node.next
list=LinkedList()
列表。追加节点(1)
列表。追加节点(2)
列表。追加节点(3)
列表。追加节点(4)
list.PopNode(0)
list.PrintList()
迄今为止的产出:
2
3
4
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
main()
File "<pyshell#31>", line 50, in main
list.PrintList( )
File "<pyshell#31>", line 27, in PrintList
node = node.next
AttributeError: 'Node' object has no attribute 'next'
2
3.
4.
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
main()
文件“”,第50行,主
list.PrintList()
打印列表中第27行的文件“”
node=node.next
AttributeError:“节点”对象没有属性“下一个”
我不确定为什么会出现错误,因为代码在技术上是有效的。此外,任何关于插入和索引函数的输入都将不胜感激 对于
插入
和索引
方法,您需要另一个节点
属性,因为您需要跟踪哪个项目位于哪个位置。我们称之为position
。您的节点
类现在将如下所示:
class Node:
def __init__(self, data, position = 0):
self.data = data
self.next_node = None
self.position = position
现在检索索引值很容易,如下所示:
def index(self,item):
current = self.head
while current != None:
if current.data == item:
return current.position
else:
current = current.next
print ("item not present in list")
至于列表更改方法,我将从一个简单的add
方法开始,该方法将项目添加到列表中最左侧的位置:
def add(self,item):
temp = Node(item) #create a new node with the `item` value
temp.next = self.head #putting this new node as the first (leftmost) item in a list is a two-step process. First step is to point the new node to the old first (lefmost) value
self.head = temp #and second is to set `LinkedList` `head` attribute to point at the new node. Done!
current = self.head #now we need to correct position values of all items. We start by assigning `current` to the head of the list
self.index_correct(current) #and we'll write helper `index_correct` method to do the actual work.
current = self.head
previous = None
while current.position != self.size() - 1:
previous = current
current = current.next
current.back = previous
self.tail = current
index\u校正方法应该做什么?只有一件事-当我们添加新项目(例如:add
,insert
等)或删除它们(remove
,pop
等)时,遍历列表以更正项目的索引位置。因此,它应该是这样的:
def index_correct(self, value):
position = 0
while value != None:
value.position = position
position += 1
value = value.next
这很简单。现在,让我们按照您的要求实现insert
方法:
def insert(self,item,position):
if position == 0:
self.add(item)
elif position > self.size():
print("position index out of range")
elif position == self.size():
self.AppendNode(item)
else:
temp = Node(item, position)
current = self.head
previous = None
while current.position != position:
previous = current
current = current.next
previous.next = temp
temp.next = current
temp.back = previous
current.back = temp
current = self.head
self.index_correct(current)
下面是我可以提出的实现(经过测试并正在工作)。这似乎是一篇老文章,但我在任何地方都找不到完整的解决方案,所以将其发布在这里
# add -- O(1)
# size -- O(1) & O(n)
# append -- O(1) & O(n)
# search -- O(n)
# remove -- O(n)
# index -- O(n)
# insert -- O(n)
# pop -- O(n) # can be O(1) if we use doubly linked list
# pop(k) -- O(k)
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 setNext(self, newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
if self.tail is None:
self.tail = temp
self.length += 1
def ssize(self): # This is O(n)
current = self.head
count = 0
while current is not None:
count += 1
current = current.getNext()
return count
def size(self): # This is O(1)
return self.length
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
# The item is the 1st item
self.head = current.getNext()
else:
if current.getNext() is None:
self.tail = previous # in case the current tail is removed
previous.setNext(current.getNext())
self.length -= 1
def __str__(self):
current = self.head
string = '['
while current is not None:
string += str(current.getData())
if current.getNext() is not None:
string += ', '
current = current.getNext()
string += ']'
return string
def sappend(self, item): # This is O(n) time complexity
current = self.head
if current:
while current.getNext() is not None:
current = current.getNext()
current.setNext(Node(item))
else:
self.head = Node(item)
def append(self, item): # This is O(1) time complexity
temp = Node(item)
last = self.tail
if last:
last.setNext(temp)
else:
self.head = temp
self.tail = temp
self.length += 1
def insert(self, index, item):
temp = Node(item)
current = self.head
previous = None
count = 0
found = False
if index > self.length-1:
raise IndexError('List Index Out Of Range')
while current is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
self.length += 1
def index(self, item):
pos = 0
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
pos += 1
if not found:
raise ValueError('Value not present in the List')
return pos
def pop(self, index=None):
if index is None:
index = self.length-1
if index > self.length-1:
raise IndexError('List Index Out Of Range')
current = self.head
previous = None
found = False
if current:
count = 0
while current.getNext() is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
self.head = current.getNext()
if current.getNext() is None:
self.tail = current.getNext()
else:
self.tail = previous
previous.setNext(current.getNext())
self.length -= 1
return current.getData()
请注意,在Node类中,您将“next”字段定义为“next_Node”。因此,口译员不知道“下一步”。因此,不是node.next,而是node.next\u node在node
中没有next
。还有next\u node
,您不需要像C中那样的python主函数?这感觉就像是David Ranum和Brad Miller使用Python解决算法和数据结构的直接结果。我也在研究这个问题,这个例子看起来太相似了,对于index
,我们是否需要在进行时分配pos
值,或者是否有一种方法可以将其添加到节点本身,然后在查找时检索该值?这样做有什么好处吗?我觉得不会,因为我们已经在做遍历列表的工作,我们将得到O(n)复杂度,但是如果我们可以事先为节点添加一个索引就好了。我的固定时间追加方法是def append(self,item):new_Node=Node(item)如果self.head==None:self.head=new\u node self.tail=new\u node其他:self.tail.set\u next(new\u node)
但它不起作用。我想我们对此有相同的基本想法,但为什么我的不起作用?你的索引实现要求在创建节点时指定索引,对吗?如果是这样的话,难道这不符合索引方法的目的吗?如果在创建节点时提供索引,为什么要请求索引?
def insert(self,item,position):
if position==0:
self.add(item)
elif position>self.size():
print("Position index is out of range")
elif position==self.size():
self.append(item)
else:
temp=Node.Node(item,position)
current=self.head
previous=None
current_position=0
while current_position!=position:
previous=current
current=current.next
current_position+=1
previous.next=temp
temp.next=current
# add -- O(1)
# size -- O(1) & O(n)
# append -- O(1) & O(n)
# search -- O(n)
# remove -- O(n)
# index -- O(n)
# insert -- O(n)
# pop -- O(n) # can be O(1) if we use doubly linked list
# pop(k) -- O(k)
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 setNext(self, newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
if self.tail is None:
self.tail = temp
self.length += 1
def ssize(self): # This is O(n)
current = self.head
count = 0
while current is not None:
count += 1
current = current.getNext()
return count
def size(self): # This is O(1)
return self.length
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
# The item is the 1st item
self.head = current.getNext()
else:
if current.getNext() is None:
self.tail = previous # in case the current tail is removed
previous.setNext(current.getNext())
self.length -= 1
def __str__(self):
current = self.head
string = '['
while current is not None:
string += str(current.getData())
if current.getNext() is not None:
string += ', '
current = current.getNext()
string += ']'
return string
def sappend(self, item): # This is O(n) time complexity
current = self.head
if current:
while current.getNext() is not None:
current = current.getNext()
current.setNext(Node(item))
else:
self.head = Node(item)
def append(self, item): # This is O(1) time complexity
temp = Node(item)
last = self.tail
if last:
last.setNext(temp)
else:
self.head = temp
self.tail = temp
self.length += 1
def insert(self, index, item):
temp = Node(item)
current = self.head
previous = None
count = 0
found = False
if index > self.length-1:
raise IndexError('List Index Out Of Range')
while current is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
self.length += 1
def index(self, item):
pos = 0
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
pos += 1
if not found:
raise ValueError('Value not present in the List')
return pos
def pop(self, index=None):
if index is None:
index = self.length-1
if index > self.length-1:
raise IndexError('List Index Out Of Range')
current = self.head
previous = None
found = False
if current:
count = 0
while current.getNext() is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
self.head = current.getNext()
if current.getNext() is None:
self.tail = current.getNext()
else:
self.tail = previous
previous.setNext(current.getNext())
self.length -= 1
return current.getData()