[英]Why does calling a function and writing statements explicitly work differently in Python?
I need an insert to head operation for a linked list that I implemented.我需要对我实现的链表进行插入头操作。 However, doing this operation by function call (like insertToHead) and writing the statements explicitly where I need them produces different results.但是,通过函数调用(如 insertToHead)执行此操作并在需要的地方显式编写语句会产生不同的结果。 I wonder which property of Python leads to that difference but I couldn't figure it out.我想知道 Python 的哪个属性会导致这种差异,但我无法弄清楚。
To be more specific, let's say that I have the following class for the linked list:更具体地说,假设我有以下链表类:
class Node:
value = None
nextNode = None
def __init__(self, value):
self.value = value
def insertToHead(self, value):
newHead = Node(value)
newHead.nextNode = self
return newHead
For a linked list with a single element (say, 2) I want to insert a node (say, 0) to the head to make linked list 0 -> 2.对于具有单个元素(例如 2)的链表,我想在头部插入一个节点(例如 0)以使链表 0 -> 2。
I created the linked list the following way我通过以下方式创建了链表
head = Node(2)
Then I tried to insert 0 to head two ways:然后我尝试插入 0 以两种方式:
newHead = Node(0)
newHead.next = head
head = newHead
Now head
is 0, not 0 -> 2.现在head
是 0,而不是 0 -> 2。
insertToHead
调用insertToHead
head = head.insertToHead(0)
head
is 0 -> 2 after this statement.在这个语句之后, head
是 0 -> 2。
Does anyone know why these two approaches result in differently?有谁知道为什么这两种方法会产生不同的结果?
You have a typo.你有一个错字。 newHead.next
should be newHead.nextNode
. newHead.next
应该是newHead.nextNode
。
A simple implementation of Singly Linked Lists:单向链表的简单实现:
class Node:
def __init__(self, value = None, nextNode = None):
self.value = value
self.nextNode = nextNode
class LinkedList:
def __init__(self):
self.head = None # will point to the head of the list
self.tail = None # will point to the tail of the list
self.size = 0 # size of the linked list
def insert_to_head(self, data):
# when push front, the head of the linked list will be Node()
self.head = Node(data, self.head)
if self.tail == None: # if tail is None, means it is a single element
self.tail = self.head
self.size += 1 # increase size by one
def __str__(self):
ret_str = ""
node = self.head
while node != None:
ret_str += str(node.value) + " -> "
node = node.nextNode
return ret_str
myLinkedList = LinkedList()
myLinkedList.insert_to_head(3)
myLinkedList.insert_to_head(2)
print(myLinkedList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.