BoJaNgLeS
BoJaNgLeS

Reputation: 61

attribute error using linked lists in python

Am new to python and am trying my hand on simulating how linked list works. I have the following code:

def mystery(x):
  a , b = x , x.next.next
  while b.next != None:
    a.next.next = b.next
    b.next = a.next
    a.next = b
    a = b
    b = b.next.next

but when ever I give it the list 'x' which is x = ['1','2','3','4', '5'], I get the following error:

  File "D:\workspace33\Quizes\src\tests.py", line 3, in mystery
a , b = x , x.next.next
AttributeError: 'list' object has no attribute 'next'

I was trying to simulate/visulaize the program on Online Python Tutor but I kept getting the same error. Can anyone let me know what am doing wrong or help me understand the process.

Upvotes: 0

Views: 96

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19219

Linked lists can be implemented with python lists if .next is replaced by [1]. Here is an example with your program so transformed.

def mystery(x):
  a , b = x, x[1][1]
  while b[1] != None:
    a[1][1] = b[1]
    b[1] = a[1]
    a[1] = b
    a = b
    b = b[1][1]
  return a, b

ll = [0, [1, [2, [3, None]]]]
print(mystery(ll))
# ([2, [1, [3, None]]], [3, None])

If you want, you can step through this program in Idle by turning on the debugger (in the Shell window) before running it from an editor window. When reaching the print line, click [over] instead of [step] (or disable the print).

Upvotes: 1

Related Questions