在链表中计算

时间:2015-03-02 19:38:53

标签: python python-2.7

我只是想确保我的getCount函数能够正常工作,因为我不知道如何测试它以确保它有效可以有人告诉我如何测试这个函数或我做错了什么?它应该计算我的链表中某个对象发生的次数。

这是ListNode导入

class ListNode(object):

    def __init__(self, item = None, link = None):

        '''creates a ListNode with the specified data value and link
        post: creates a ListNode with the specified data value and link'''

        self.item = item
        self.link = link

from ListNode import ListNode

class LinkedList(object):

    #--------------------------------------------------------------

    def __init__(self, seq=()):

        """ Pre: Creates a Linked List
        Post: Creates a list containing the items in the seq=()"""

        if seq == ():

            # If there is no items to be put into the list, then it creates an empty one.
            self.head = None

        else:

            # Creates a node for the first item.
            self.head = ListNode(seq[0], None)

            # If there are remaining items, then they're added while keeping track of the last node.
            last = self.head
            for item in seq[1:]:
                last.link = ListNode(item, None)
                last = last.link

        self.size = len(seq)

    def getCount(self, position):

        ''' This function counts the amount of times a certain item is in the Linked List.'''

        count = 0
        if self.head == position:
            count = 1
        if self.head.link is None:
            return count
        return count + getCount(self.head.link, position)

     def __copy__(self):

        ''' Post: Returns a new Linked List object that is a shallow copy of self.'''

        a = LinkedList()
        node = self.head
        while node is not None:
            a.append(node.item)
            node = node.link
        return a

    #-----------------------------------------------------------------

    def __iter__(self):

        return LinkedListIterator(self.head)

#---------------------------------------------------------------------

class LinkedListIterator(object):

    #-----------------------------------------------------------------

    def __init__(self, head):
        self.currnode = head

    #-----------------------------------------------------------------

    def next(self):
        if self.currnode is None:
            raise StopIteration
        else:
            item = self.currnode.item
            self.currnode = self.currnode.link
            return item

    #-----------------------------------------------------------------

希望我发布了足够的代码供你们查看问题。我只想找到一种方法来测试我的计数是否有效,以及我是否需要知道如何使其工作。

1 个答案:

答案 0 :(得分:0)

您的LinkedList.getCount()方法有几个问题:

  • 如果它等于self.head,它会尝试计算position,但self.head节点,{{1}的实例}。它永远不会等于你想要计算的值。

  • 它尝试递归使用该方法,但没有全局ListNode函数。

这里不需要使用递归;只需继续抓住“当前”中的下一个节点,直到用完为止,并每次与getCount()进行比较:

node.item
相关问题