弹出链表的最后一个元素时出现意外输出

时间:2019-02-08 16:57:45

标签: python linked-list

我制作了一个Node和Deque类来表示一个双链表。我编写了一个函数以弹出列表的最后一项,但是执行该函数后,它将弹出第一个元素。

我的预期输出:

scope=provided

我的链表功能文件:

my_list.push_front(1)
my_list.push_front(2)
my_list.push_front(3)
linked list is [3, 2, 1]
my_list.pop_back() --> [3,2]

我的主文件:

class Node:
    """
    Initialize empty node
    """

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

class Deque:
    """
    A double-ended queue
    """

    def __init__(self):
        """
        Initializes an empty Deque
        """
        self.head = None
        self.size = 1

    def __len__(self):
        """
        Computes the number of elements in the Deque
        :return: The size of the Deque
        """
        counter = 1
        current = self.head
        if self.head is None:
            return 0
        while current.next is not None:
            counter += 1
            current = current.next
        return counter

    def push_front(self, e): #needs work
        """
        Inserts an element at the front of the Deque
        :param e: An element to insert
        """
        new_head = Node(data = e, next = self.head)

        if self.head:
            self.head.prev = new_head
        self.head = new_head

    def pop_back(self):
        """
        Removes and returns the last element
        :return: The (former) last element
        """
        if self.head == None:
            raise IndexError

        curr = self.head
        while curr.next:
            curr = curr.next

        save = self.head.data
        self.head = self.head.next

        self.size -= 1
        return save

    def listprint(self, node):
        """
        Prints each element of the node front to back
        :param node:
        """
        while (node is not None):
            print(node.data)
            last = node
            node = node.next

在我的pop_back()函数中,我想遍历直到链表的末尾,然后将self.head设置为self.head.next并将链表的大小减小1。

1 个答案:

答案 0 :(得分:1)

这就是我认为的问题:

    save = self.head.data
    self.head = self.head.next

您要删除最后一个,但实际上您正在更改头部的参考。如果要更改最后一个的引用,则应执行以下操作:

    while curr.next.next:   # This allows you to stand on the previous of the last one
        curr = curr.next

    save = curr.next
    curr.next = None

    self.size -= 1
    return save

您在此处实际执行的操作是弹出而不是出队