title: Python:Moving through linked list 'next'
body: <p>I'm working through Cracking the Coding Interview 6th ed and am unsure of their definition of 'next'</p>
  
  <p>Their code defining "Linked List" can be found <a href="https://github.com/careercup/CtCI-6th-Edition-Python/blob/master/Chapter%202/LinkedList.py" rel="nofollow noreferrer">here</a>. I'm trying out the second exercise, which is to find the kth from the end element of a random linked list.</p>
  
  <p>My code:</p>
  
  <pre><code>from LinkedList import LinkedList
  
  def kth_to_last(ll, k):
      num_seen = 0
      length_list = count_length(ll)
  
      val = ll.head
  
      # ISSUE IS HERE
      while val.next != None:
          print 'hi'
          val.next = val.next.next
  
      """
      while num_seen &lt; (length_list - k):
          val = val.next
          num_seen += 1
      """
      return val.next
  
  
  # Counts length of LL
  def count_length(ll):
      val = ll.head
      count = 1
      while val.next != None:
          count += 1
          val.next = val.next.next
      return count
  
  
  ll = LinkedList()
  ll.generate(10, 0, 99)
  print(ll)
  kth_to_last(ll, 3)
  </code></pre>
  
  <p>It's counting through the list just fine, but for the first definition, I can't get it to move through the linked list (it won't print 'hi' at all). </p>
  
  <p>I plan to do something like I have commented out (they also have 'tail' defined so I might try that out), but I'm confused why I can move through the list just fine within 'count_length,' but then I can't seem to move through it within 'kth_to_last'?</p>
  
  <p>Edit: To clarify, if I print val.next within 'kth_to_last' it has a value of 'None'</p>
  
  <p>Edit2:</p>
  
  <p>If I comment out the "count_length," the next proceeds just fine. Could someone explain to me why calling this function alters next. Has it stuck me at the end of the list?</p>
  
  <p>My code:</p>
  
  <pre><code>def kth_to_last(ll, k):
      """
      num_seen = 0
      length_list = count_length(ll)
      """
  
      # Start at head
      val = ll.head
      while val.next != None:
          print val.next
          val = val.next
  </code></pre>
  
  <p>This prints the list just fine</p>