【问题标题】:Suspicious temp = temp.next [closed]可疑温度 = temp.next [关闭]
【发布时间】:2020-11-19 12:04:02
【问题描述】:

我在 python 中练习了一些链表问题,这是我从用户那里提供链表节点然后打印它们的完整代码:

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

class linkList:
    def __init__(self):
        self.head = None

# In this program first we get linked list nodes from users 
# and then we will try to print all the nodes


GivenNode = input("please enter the first node")
OurList = linkList()
OurList.head = Node(GivenNode)

# Since now , temp is our node that were doing something on it:
temp = OurList.head

while (1):


    GivenNode = input("Please enter the next node and if that ends please type end:")

    if(GivenNode == "end"):
        break

    temp.next = Node(GivenNode)
    temp = temp.next

# Now we want to print all nodes 
temp_2 = OurList.head

while( temp_2.next != None ):

    print(temp_2.data)
    temp_2=temp_2.next

我不明白:

temp = temp.next

我认为这会删除临时记忆... 但是当我想打印所有节点时,它们已经存在了! 怎么样?

【问题讨论】:

  • "我认为这会删除临时内存。"好吧,它没有。为什么你这么想? Python 没有'任何直接控制内存管理。您不能手动删除对象。
  • @ juanpa.arrivillaga 但是当我们想删除一个笔记时,我们如何使用 temp=None?

标签: python singly-linked-list


【解决方案1】:

temp 只是一个参考。当您初始化OurList 并将Node 添加到其head 时,您已经在内存中创建了实例。 temp 只是对这些实例的引用,可以随时更新。

让我们从temp = OurList.head开始。

GivenNode = 1
OurList = linkList()
OurList.head = Node(GivenNode)  // Node1

temp = OurList.head  // here temp = Node1

GivenNode = 2 
temp.next = Node(GivenNode)  // temp = Node1, temp.next = OurList.head.next = Node2
temp = temp.next  // temp = Node2

看到了吗? 首先,初始化了Node 的类实例。这个类有一个内存地址Address A,存储在LinkedList实例的head中。

在每个循环中,执行两个操作。

  1. Node 类的next 属性使用temp.next 指向一个新的Node 实例,存储在Address B
  2. 在初始化之后,temp 被重新初始化为Node 实例Address B。所以下一个循环将在Address CNode 实例,依此类推。

因此,实例被指向另一个,一切都在内存中,temp 只是不断地从一个节点到另一个节点,并在此过程中创建新的连接。

现在,当您初始化temp_2 = OurList.head 时,temp_2 现在指向内存地址Address A 上的一个实例,并且循环只遍历了temp 在上一个循环中建立的所有连接。

简而言之,temptemp_2 只是在任何给定时间点指向某个实例的一些引用。您只是在任何给定时间点更改这些变量指向的实例,整个数据在内存中仍然完好无损,并且可以被OurList.headOurList.head.nextOurList.head.next.next 等引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多