双链路lis中节点前的插入

2024-09-30 12:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个节点之前插入一个节点到双链接中列表。之后我做手术没有得到正确的结果。在

class createnode:
  def __init__(self,data):
      self.data=data
      self.next=None
      self.prev=None

class Unordered_list: 
  def __init__(self):
   self.head=None 
######Insertion at the starting###
  def buildlst(self,data):
    node=createnode(data)
    if self.head is None:
     self.head=node
    else:
     node.next=self.head
     node.prev=None
     self.head=node
#######INsertion at the end####
  def buildlstend(self,data):
    node=createnode(data)
    ptr=self.head
    while(ptr.next):
      ptr=ptr.next
    ptr.next=node
    ptr=node.prev

#######INsertion before some node i.e searched node####
  def insertbeforenode(self,data,srch_data):
    node=createnode(data)
    ptr=self.head
    while(ptr):  
      if ptr.data==srch_data:
        node.prev=ptr.prev
        node.next=ptr
        ptr.prev=node 
      ptr=ptr.next


########Printitng the list########      
  def printlist(self):
     temp=self.head      
     while(temp):
      print(temp.data)  
      temp=temp.next    

A=Unordered_list()
A.buildlst(10)
A.buildlst(20)
A.buildlstend(30)
A.printlist()
print("Here i will insert a new node 50 before 10")
A.insertbeforenode(50,10)
A.printlist()

我的列表看起来像20,10,30。我想在10之前有新的节点,但它打印的我还是一样的结果。有我的程序是用python编写的,因此无法从中收集到很多信息。 insertbeforenode是我调用的函数。在


Tags: theselfnonenodedata节点deftemp
1条回答
网友
1楼 · 发布于 2024-09-30 12:31:39

Python支持使用内置机制来处理列表,您可以轻松地执行以下操作:

list = []
list.append(10)
list.insert(0, 20)
list.append(30)
list.insert(1, 50)

更多示例请参见官方文档https://docs.python.org/3/tutorial/datastructures.html。在

不管怎样,如果你想自己编写一个双重链接列表,我对你的代码做了一些修改:

^{pr2}$

我在做更改的地方放了一个箭头(#<;)。在使用指针时有一些错误和其他错误。请试试这个让我知道!在

相关问题 更多 >

    热门问题