Ken Lambert著《数据结构》第九章编程项目

列表迭代器

"""
File: linkedlistiterator.py
Author: Zhu nw
"""
from node import TwoWayNode

class LinkedListIterator(object):
    """Represents the list iterator for an linked list."""

    def __init__(self, backingStore):
        self._backingStore = backingStore
        self._modCount = backingStore.getModCount()
        self.first()

    def first(self):
        """Returns the cursor to the beginning of the backing store."""
        self._cursor = self._backingStore._head.next
        self._lastItemPos = self._backingStore._head

    def hasNext(self):
        """Returns True if the iterator has a next item or False otherwise."""
        return not self._cursor is self._backingStore._head

    def next(self):
        """Preconditions: hasNext returns True
        The list has not been modified except by this iterator's mutators.
        Returns the current item and advances the cursor to the next item.
        Postcondition: lastItemPos is now defined.
        Raises: ValueError if no next item.
        AttributeError if illegal mutation of backing store."""
        if not self.hasNext():
            raise ValueError("No next item in list iterator")
        if self._modCount != self._backingStore.getModCount():
            raise AttributeError("Illegal modification of backing store")
        self._lastItemPos = self._cursor
        self._cursor = self._cursor.next
        return self._lastItemPos.data

    def last(self):
        """Moves the cursor to the end of the backing store."""
        self._cursor = self._backingStore._head.previous
        self._lastItemPos = self._backingStore._head

    def hasPrevious(self):
        """Returns True if the iterator has a previous item or False otherwise."""
        return not self._cursor is self._backingStore._head

    def previous(self):
        """Preconditions: hasPrevious returns True
        The list has not been modified except by this iterator's mutators.
        Returns the current item and moves the cursor to the previous item.
        Postcondition: lastItemPos is now defined.
        Raises: ValueError if no next item.
        AttributeError if illegal mutation of backing store."""
        if not self.hasPrevious():
            raise ValueError("No previous item in list iterator")
        if self._modCount != self._backingStore.getModCount():
            raise AttributeError("Illegal modification of backing store")
        self._lastItemPos = self._cursor
        self._cursor = self._cursor.previous

        return self._lastItemPos.data

    def replace(self, item):
        """Preconditions: the current position is defined.
        The list has not been modified except by this iterator's mutators.
        Replaces the items at the current position with item.
        Raises: AttibuteError if position is not defined.
        AttributeError if illegal mutation of backing store."""
        if self._lastItemPos is self._backingStore._head:
            raise AttributeError("The current position is undefined.")
        if self._modCount != self._backingStore.getModCount():
            raise AttributeError("List has been modified illegally.")
        self._lastItemPos.data = item
        self._lastItemPos = self._backingStore._head

    def insert(self, item):         
        """Preconditions:
        The list has not been modified except by this iterator's mutators.
        Adds item to the end if the current position is undefined, or
        inserts it at that position.
        Raises: AttributeError if illegal mutation of backing store."""
        if self._modCount != self._backingStore.getModCount():
            raise AttributeError("List has been modified illegally.")
        if self._lastItemPos is self._backingStore._head:
            #self._backingStore.add(item)
            newNode = TwoWayNode(item, self._lastItemPos.previous, self._lastItemPos)
            self._lastItemPos.previous.next = newNode
            self._lastItemPos.previous = newNode
            self._backingStore.incModCount()
            self._backingStore.incSize()
        else:
            #self._backingStore.insert(self._lastItemPos, item)
            #self._lastItemPos = -1
            newNode = TwoWayNode(item, self._lastItemPos.previous, self._lastItemPos)
            self._lastItemPos.previous.next = newNode
            self._lastItemPos.previous = newNode
            self._backingStore.incModCount()
            self._backingStore.incSize()
            self._lastItemPos = self._backingStore._head
        self._modCount += 1

    def remove(self):         
        """Preconditions: the current position is defined.
        The list has not been modified except by this iterator's mutators.
        Pops the item at the current position.
        Raises: AttibuteError if position is not defined.
        AttributeError if illegal mutation of backing store."""
        if self._lastItemPos is self._backingStore._head:
            raise AttributeError("The current position is undefined.")
        if self._modCount != self._backingStore.getModCount():
            raise AttributeError("List has been modified illegally.")
        #item = self._backingStore.pop(self._lastItemPos)
        #item = self._lastItemPos
        self._lastItemPos.previous.next = self._lastItemPos.next
        self._lastItemPos.next.previous = self._lastItemPos.previous
        # If the item removed was obtained via next, move cursor back
        #if self._lastItemPos < self._cursor:
        #    self._cursor -= 1
        self._modCount += 1
        self._backingStore.incModCount()
        self._backingStore.decSize()
        self._lastItemPos = self._backingStore._head

测试代码

"""
File: testlistiterator.py

A tester program for list iterator implementation.
"""

from arraylist import ArrayList
from linkedlist import LinkedList
#from arraysortedlist import ArraySortedList

def test(listType):
    """Expects a list type as an argument and runs some tests
    on objects of that type.""" 
    print("Create a list with 1-9")
    lyst = listType(range(1, 10))
    print("Length:", len(lyst))
    print("Items (first to last):", lyst)

    # Create and use a list iterator
    listIterator = lyst.listIterator()
    print("Forward traversal: ", end="")
    listIterator.first()
    while listIterator.hasNext(): 
            print(listIterator.next(), end = " ")

    print("\nBackward traversal: ", end="")
    listIterator.last()
    while listIterator.hasPrevious(): 
            print(listIterator.previous(), end=" ")

    print("\nInserting 10 before 3: ", end="")
    listIterator.first()
    for count in range(3):
            listIterator.next()
    listIterator.insert(10)
    print(lyst)
    print("Removing 2: ", end="")
    listIterator.first()
    for count in range(2): 
            listIterator.next()
    listIterator.remove()
    print(lyst)

    print("Removing all items")
    listIterator.first()
    while listIterator.hasNext():
            listIterator.next()
            listIterator.remove()
    print("Length:", len(lyst))



test(ArrayList)
print("\n\n")
test(LinkedList)

测试结果

Create a list with 1-9
Length: 9
Items (first to last): [1, 2, 3, 4, 5, 6, 7, 8, 9]
Forward traversal: 1 2 3 4 5 6 7 8 9
Backward traversal: 9 8 7 6 5 4 3 2 1
Inserting 10 before 3: [1, 2, 10, 3, 4, 5, 6, 7, 8, 9]
Removing 2: [1, 10, 3, 4, 5, 6, 7, 8, 9]
Removing all items
Length: 0



Create a list with 1-9
Length: 9
Items (first to last): [1, 2, 3, 4, 5, 6, 7, 8, 9]
Forward traversal: 1 2 3 4 5 6 7 8 9
Backward traversal: 9 8 7 6 5 4 3 2 1
Inserting 10 before 3: [1, 2, 10, 3, 4, 5, 6, 7, 8, 9]
Removing 2: [1, 10, 3, 4, 5, 6, 7, 8, 9]
Removing all items
Length: 0

猜你喜欢

转载自blog.csdn.net/sinat_39013092/article/details/81273594