【问题标题】:Adding recursive copy method to linked list implementation in Python?将递归复制方法添加到 Python 中的链表实现?
【发布时间】:2018-06-16 04:37:15
【问题描述】:

您好,我在 Python 中实现了一个链表,我得到了可以将链表复制到另一个链表的这段代码但我不明白为什么它插入到 0 索引处?

那复制的列表不会倒过来吗?但是我尝试运行它,输出是正确的并且是有序的?

我的插入函数

def insert(self, index, item):
    if index<0 and index<-1*len(self):
        raise IndexError("Negative index out of range")
    elif index>0 and index>=len(self):
        raise IndexError("Positive index out of range")

    if index==0:
        self.head=Node(item,self.head)

    elif index>0:
        node=self._get_node(index-1)
        node.next=Node(item,node.next)

    else:
        node=self._get_node(index+len(self))
        node.next=Node(item,node.next)
    self.count+=1

我的复制功能

 def copy(self):
    new_list=linkedList()
    self._copy_aux_(self.head,new_list)
    return new_list

 def _copy_aux_(self, node, new_list):
    if node is not None:
        self._copy_aux_(node.next, new_list)
        new_list.insert(0,node.item)

有人可以帮忙解释一下吗?任何帮助将不胜感激!

编辑:好吧,显然它首先插入最后一项?为什么会这样?

【问题讨论】:

    标签: python recursion linked-list


    【解决方案1】:

    1 - 当您调用索引等于零的插入时,您会预先插入列表项,即在 head 指向的位置(参见方法 def insert(self, index, item): 2 - 当方法 copy 被调用时,方法 def _copy_aux_(self, node, new_list): 被递归调用,直到到达列表的最后一项,它的 node.next 等于 None。 3 - 之后,每次从_copy_aux_方法返回后,它开始将new_list中的itens从最后一项插入到第一项,这给出了正确的顺序。

    我建议包括打印来跟踪列表复制递归,如下代码:

    def copy(self):
            print('Trace copy:')
            new_list=linkedList()
            self._copy_aux_(self.head,new_list)
            return new_list
    
        def _copy_aux(self, node, new_list):
            if node is not None:
                self._copy_aux_(node.next, new_list)
                new_list.insert(0,node.item)
                print(new_list)
    

    然后运行以下示例(取自https://repl.it/@MuhammadFermi/week8-2):

    list = linkedList()
    list.insert(0, 3)
    list.insert(0, 9)
    list.insert(0, 2)
    list.insert(0, 5)
    list.insert(0, 1)
    list.insert(2, 6)
    list.insert(10, 7)
    print(list)
    print(len(list))
    print(3 in list)
    list2 = list.copy()
    print('list2 =')
    print(list2)
    

    你应该得到以下结果:

    1, 5, 6, 2, 9, 3, 7, 
    7
    True
    Trace copy:
    7, 
    3, 7, 
    9, 3, 7, 
    2, 9, 3, 7, 
    6, 2, 9, 3, 7, 
    5, 6, 2, 9, 3, 7, 
    1, 5, 6, 2, 9, 3, 7, 
    list2 =
    1, 5, 6, 2, 9, 3, 7, 
    
    Process finished with exit code 0
    

    【讨论】:

      【解决方案2】:

      我建议展平您的列表,然后将值重新插入到新列表中:

      class LinkedList:
         def __init__(self, value = None):
           self.head = value
           self._next = None
         def insert_node(self, _val):
           if self.head is None:
             self.head = _val   
           else:
             getattr(self._next, 'insert_node', lambda x:setattr(self, '_next', LinkedList(x)))(_val)
         def flatten(self):
           return [self.head, *getattr(self._next, 'flatten', lambda :[])()]
         @classmethod
         def copy(cls, l):
            t = cls()
            for i in l.flatten():
              t.insert_node(i)
            return t
      
      l = LinkedList()
      for i in range(10):
        l.insert_node(i)
      new_l = LinkedList.copy(l)
      

      【讨论】:

        猜你喜欢
        • 2015-05-06
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多