Linked list- 当添加节点时,current vs. current.next

huangapple go评论62阅读模式
英文:

Linked list- current vs. current.next when appending

问题

Node:

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

def add() part one:

def add(self, newData):
    
    if self.head is None:
        self.head = Node(newData)
        return
  
    current = self.head

def add() part 2:

Why does this work?
    while current.next:
        current = current.next
    
    current.next =  Node(newData)

And this doesn't?

    while current:
        current = current.next
            
    current = Node(newData)

Aren't "current.next" in the first one and "current" in the second one the same?

英文:

Node:

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

def add() part one:

def add(self, newData):
    
    if self.head is None:
        self.head = Node(newData)
        return
  
    current = self.head
   

def add() part 2

Why does this work?

    while current.next:
        current = current.next
    
    current.next =  Node(newData)

And this doesn't?

    while current:
        current = current.next
            
    current = Node(newData)

Aren't "current.next" in first one and "current" in second one same?

答案1

得分: 2

两个循环代码之间唯一的区别在于最后一行,在那里你要么赋值给 current.next,要么赋值给 current。它们实际上做了完全不同的事情。

当你赋值给 current.next 时,你正在修改 current 引用的 Node 对象的属性。这个改变是就地进行的,所以你会通过其他引用(比如链表中之前的节点)看到这个改变。这就是你想要发生的事情。

在修改后的版本中,当你赋值给 current 时,你只是重新绑定了本地命名空间中的变量名称。你没有改变任何节点!你可以将其与以下代码进行比较:

a = 1
b = a
b = 2
print(a) # 仍然打印 1

这里的 b 在你的代码的第二个版本中就相当于 currenta 是列表中最后一个节点的 next 属性(在代码的工作版本中称为 current.next)。重新绑定本地名称 b 不会改变对相同值的其他引用。

英文:

The only difference between the two loop codes is the last line, where you either assign to current.next or to current. Those do fundamentally different things.

When you assign to current.next, you're modifying an attribute of the Node object referenced by current. That change happens in place, so you'll see the change through other references (like the chain of nodes earlier in the list). That's what you want to happen.

In the modified version, when you assign to current, you're only rebinding the variable name in the local namespace. You're not changing any node! You could compare it to:

a = 1
b = a
b = 2
print(a) # still prints 1

Here b is current in the second version of your code. a is the next attribute of the last node of the list (which was called current.next in the working version of the code). Rebinding the local name b doesn't change the other reference to the same value.

huangapple
  • 本文由 发表于 2023年2月16日 06:03:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定