python linklist pointer and size
<p>I am a rookie python programmer. I see the leetcode's definition of a linked list below. I got 2 questions for this concept, any help would be appreciated. Thanks in advance</p>

<pre><code># Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
</code></pre>

<p>Q1 Just wonder what is the type of the "self.next", I know in C++, it should be a pointer that represents the address of the next node. But python does not have that type, so I am confused what type "next" is.</p>

<p>Q2 Some tell me next is just a name. If that is the case, I run the code below, </p>

<pre><code>head =ListNode(1)
print sys.getsizeof(head)
head.next = ListNode(2)
print sys.getsizeof(head)
</code></pre>

<p>first the head.next is 'None', and then it is assigned to another ListNode type,
but I get the same size of head before and after this change, which I think the size of head should be larger since one of its member (next) is changed from None type to ListNode type.  I am just confused about this, thank you so much!</p>

<p>PS. In my understanding, if I keep adding new nodes to the linklist, the head will be larger and larger since there are more and more 'nested' member 'next', just point out where I get wrong, thanks.</p>

<p>Question 1:</p>

<p>Python variables are dynamically typed. (i.e. a variable could hold an int, and then hold a list, and then any other arbitrary object, etc).</p>

<p>In your case, <code>Head.next</code> starts by referencing, <code>None</code> a <code>NoneType</code> object.</p>

<p>After you assign it a different value (<code>ListNode(2)</code>), the <code>Head.next</code> now references the newly created <code>ListNode</code> object.</p>

<p>Question 2:</p>

<p>Why doesn't the size change.
I'm not an expert on how python's <code>sys.getsizeof</code> works, but from what I can gather, is that List.next in both cases is a reference variable (i.e. a variable that references some other object). The size doesn't change because <code>sys.getsizeof</code> finds the size of the object's variables. Where <code>Head.next</code> is just a reference to some other object in both cases.</p>

<p>See, <a href="http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python">How do I determine the size of an object in Python?</a>, for more complete answers on how <code>sys.getsizeof</code> works.</p>

python c++ class pointers linked-list