在Positional Linked List类中使用交换方法而不创建新节点。

时间:2018-04-20 15:31:11

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

明智的。我在Positional Linked List类中实现swap方法时遇到困难。交换方法将输入两个位置,“p”和“q”,它们将交换位置并重新链接现有节点。任何帮助表示赞赏。 这就是我到目前为止所做的:

$array[$row ['id']] [$row ['version']] = $row['filename']

它适用于某些情况但不是全部。我一直在考虑标题和预告片节点以及这适用的各种条件但是我遇到了很多麻烦。

这是继承自双向链接列表的类位置链接列表。

def swap(self, p, q):  # Problem 7.34
    valid_position = self._validate(p)
    valid_position2 = self._validate(q)
    element_p = valid_position._element
    element_q = valid_position2._element
    position_next = valid_position._next
    position_prev = valid_position._prev
    valid_position._next = valid_position2._next
    valid_position._prev = valid_position2._prev
    valid_position2._next = position_next
    valid_position2._prev = position_prev
    valid_position._element = element_q
    valid_position2._element = element_p

这是Doubly Linked List类:

# Abstract Data Type : Positional List
# A positional list PL supports

# len(PL)
# PL.is_empty()

# Accessor Methods (getters)
# iter(PL) : Return a forward iterator (uses yield)
# PL.first(), PL.last() : Return position of first (last) element, or None
# if empty
# PL.before(p), PL.after(p) : Return the position immediately before (after) p,
# or None if p is first (last)


# Mutators Methods (setters)
# PL.add_first(e), PL.add_last(e) : Insert new element e in front (back) and return position
# PL.add_before(p, e), PL.add_after(p, e) : Insert new element e just before (after) p, return
# position
# PL.delete(p) : Remove and return element at position p. Also invalidates position p.
# PL.replace(p, e) : Replace and return element replaced at position p.

from DoublyLinkedList import _DoublyLinkedList as dlb

class PositionalList(dlb):
    # ------ nested Position class ---------------
    class Position:

        def __init__(self, container, node):
            self._container = container    # reference to linked list that 
            contains
                                           # node at this position
            self._node = node              # reference to node pointed to by 
        # this position

        def element(self):
            return self._node._element

        def __eq__(self, other):
            """Return True if other is a Position representing teh same 
            location as self."""
            return type(other) is type(self) and other._node is self._node

        def __ne__(self, other):           # !=
            return not (self == other)

    # --------------- private position Validation method
    # possible errors: p is not a Position, p is not in the current list, p 
    # is no longer valid
    # purpose of method: return the node pointed to by p if p is a valid 
    # position
    # self in this scope refers to an instance of a doubly linked list

    def _validate(self, p):
        """Return position's node, or raise an exception."""
        if not isinstance(p, self.Position):
            raise TypeError("p must be of type Position.")
        # if the list that contains p is not in the current list raise 
        # ValueError
        if p._container is not self:
            raise ValueError("p does not belong to this container.")
        if p._node._next is None:    # means underlying node has been 
        invalidated
            raise ValueError("p is no longer valid.")
        return p._node

    # --------------- private method to create a position
    def _make_position(self, node):
        """Return Poisition instance for a given node, None if node is a 
        sentinel."""
        if node is self.header or node is self.trailer:
            return None
        else:
            return self.Position(self, node)

    # ----------------- accessor methods -------------------------
    def first(self):
        return self._make_position(self.header._next)

    def last(self):
        return self._make_position(self.trailer._prev)

    def before(self, p):
        node = self._validate(p)
        return self._make_position(node._prev)

    def after(self, p):
        node = self._validate(p)
        return self._make_position(node._next)

    def __iter__(self):
        """Forward iterator of list elements."""
        # Allows the use of next()
        # Allows embedding into for loops
        pointer = self.first()
        while pointer is not None:
            yield pointer.element()  #return element stored at this position
            pointer = self.after(pointer)  # moves the pointer "forward"

    def __reversed__(self): # Problem 7.15
        """Backward iterator of list elements."""
        pointer = self.last()
        while pointer is not None:
            yield pointer.element()
            pointer = self.before(pointer)


    def find(self, e):  # Problem 7.13
        pointer = self.first()
        while e != pointer.element():
            if e == pointer.element():
                return pointer.element()
            pointer = pointer.after(pointer)

    # ---------------  mutator methods
    # override the _insert_between() from parent _DoublyLinkedList class
    # to allow returning a position rather than a node
    def _insert_between(self, e, predecessor, successor):
        node = super().insert_between(e, predecessor, successor)
        return self._make_position(node)

    def add_first(self, e):
        """Insert new element e in front and return a position."""
        return self._insert_between(e, self.header, self.header._next)

    def add_last(self, e):
        return self._insert_between(e, self.trailer._prev, self.trailer)

    def add_before(self, p, e):
        valid_position = self._validate(p)
        return self._insert_between(e, valid_position._prev, valid_position)

    def add_after(self, p, e):
        valid_position = self._validate(p)
        return self._insert_between(e, valid_position, valid_position._next)

    def delete(self, p):
        """Remove and return element at position p. Invalidate position 
        p."""
        valid_position = self._validate(p)
        #p._container = None
        return self.delete_node(valid_position)

    def replace(self, p, e):
        """Replace and return element at position p."""
        valid_position = self._validate(p)
        element_to_return = valid_position._element
        valid_position._element = e
        return element_to_return

    def swap(self, p, q):  # Problem 7.34
        valid_position = self._validate(p)
        valid_position2 = self._validate(q)
        element_p = valid_position._element
        element_q = valid_position2._element
        position_next = valid_position._next
        position_prev = valid_position._prev
        valid_position._next = valid_position2._next
        valid_position._prev = valid_position2._prev
        valid_position2._next = position_next
        valid_position2._prev = position_prev
        valid_position._element = element_q
        valid_position2._element = element_p

0 个答案:

没有答案