返回值失败

时间:2018-03-17 23:42:41

标签: python-3.x return-value doubly-linked-list

我正在处理一个双向链表,我无法返回值,我从列表中间删除了一个项目。我不确定为什么,并会欣赏第二双眼睛看到这一点。

如果我追加三个数字然后删除索引imgPath = 'images/' + sport.name.toLowerCase() + '.png'; 处的数字,它应该返回索引1,处的值。

1

1 个答案:

答案 0 :(得分:0)

我添加了addValue()debug()方法(提示:阅读How to debug small programs (#1))。

为了清楚起见,我修改了开始/结束节点以获得值。我减少/重构(重写)你的remove方法 - 它有一些不必要的开销和指针错误。对于双链表,你必须同时处理下面和前面的元素,并正确地更改所有指针以保持链的完整性。

class Linked_List: 
    class __Node: 
      def __init__(self, val):
          self.val = val
          self.next = None
          self.prev = None
          return 


    def __init__(self):
      self.__header = self.__Node('Start')   # start node
      self.__trailer = self.__Node('End')    # end node
      self.__header.next = self.__trailer 
      self.__trailer.prev = self.__header
      self.__size = 0


    def debug(self):
        cur = self.__header 
        print("prev.val  cur.val  next.val")
        i = 0
        while cur:
            print("  " * i, f'{cur.prev.val if cur.prev else None}  {cur.val}  {cur.next.val if cur.next else None}')
            i+=1
            cur = cur.next


    def addValue(self, val):
        """Adds the str of val at the end."""
        n = self.__Node(str(val))
        n.next = self.__trailer   
        n.prev = self.__trailer.prev
        self.__trailer.prev.next = n
        self.__trailer.prev = n
        self.__size += 1


    def remove_element_at(self, index):
        if not (0 <= index < self.__size ): # simplified
            # better message on error
            raise IndexError (f'Index {index} out of bounds [0,{self.__size-1}]')

        cur = self.__header.next     # simplified, element_to_return not needed

        # there is no need for special cases for 0 or size - this will handle all
        for i in range(0, index):
            cur = cur.next   # go ever deeper, if we are at 0 or self.__size not entering
        cur.prev.next = cur.next  # repointer prev's next to our next
        cur.next.prev = cur.prev  # repointer next's prev to our prev
        self.__size -= 1          # decrease size
        return str(cur.val)       # return our value


k = Linked_List()

for n in range(5):
    k.addValue(n)
k.debug()
removed = k.remove_element_at(4)
k.debug()
print(f'removed: {removed}')

输出:

prev.val  cur.val  next.val
 None  Start  0
   Start  0  1
     0  1  2
       1  2  3
         2  3  4
           3  4  End
             4  End  None
 None  Start  0
   Start  0  1
     0  1  2
       1  2  3
         2  3  End
           3  End  None
removed: 4

编辑:

我的添加方法是自建的。确保你正确获取指针 - 使用调试方法确保cur.prev.next指向curcur.next.prev也指向cur