为什么两个代码看起来相同,但是一个不起作用? Python链表数据结构

感谢您提前阅读问题。

我正在通过Python研究链表数据结构。下面两种方法push(),push1()困扰了我。

类Node(object):

def __init__(self, value):
    self.value = value
    self.next = None

def __repr__(self):
    nval = self.value and self.next.value or None
    return f"[{self.value}:{repr(nval)}]"

类LinkedListController(object):

def __init__(self):
    self.begin = None

# Appends new value at the end of the list
def push(self, obj):
    if not self.begin:
        self.begin = Node(obj)
    else:
        n = self.begin
        while n.next :
            n = n.next
        n.next = Node(obj)

def push1(self, obj):
    if not self.begin:
        self.begin = Node(obj)
    else:
        while self.begin.next:
            self.begin = self.begin.next
        self.begin.next = Node(obj)

# Counts the number of elements in the list
def count(self):
    current_node = self.begin
    count = 0

    while current_node:
        count = count + 1
        current_node = current_node.next
    return count

下面是测试代码:

from unittest import TestCase
from data_structure.single_linked_list_without_endnode import LinkedListController as node_controller

类TestLinkedList(TestCase):

def test_push(self):
    colors = node_controller()
    colors.push("Pathalon Blue")
    self.assertEquals(colors.count(), 1)

    colors.push("Ultramarine Blue")
    self.assertEquals(colors.count(), 2)

    colors.push("Blaring Sun")
    self.assertEquals(colors.count(), 3)

    animals = node_controller()
    animals.push1("Dog")
    self.assertEquals(animals.count(), 1)

    animals.push1("Cat")
    self.assertEquals(animals.count(), 2)

    animals.push1("Cow")
    self.assertEquals(animals.count(), 3)
  1. The only difference between push() and push1() is reference 'n', other than that I see the same logic but why push1() does not work ?

    Traceback (most recent call last): File "C:\Users\Dell\projects\data_structure\tests\test_single_linked_list_without_endnode.py", line 24, in test_push self.assertEquals(animals.count(), 3) AssertionError: 2 != 3

  2. In the first push method,n.next = Node(obj) is just assigning to reference data 'n', not to self.begin. And I think self.begin should be still None since we did not do anything like self.begin.next = Node(obj), but the test is working fine. How..?

非常感谢