0

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.

4
  • Why do you think lists have a next attribute? (they don't) Commented Feb 23, 2015 at 18:43
  • Python lists, such as your x = ['1','2','3','4', '5'], are not linked lists. Commented Feb 23, 2015 at 18:45
  • @TimCastelijns- Thanks, how would I go about using the program? Commented Feb 23, 2015 at 18:47
  • @BoJaNgLeS: I suggest you Google "Python linked list" for lots of information on implementing linked lists in Python. (It's not a native feature of the language; you have to roll your own.) Commented Feb 23, 2015 at 18:49

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

@TerryJanReedy- does this program do the exact same thing as the original one?
In terms of how links are accessed and manipulated, yes. I did the indicated Find/Replace-all in the mystery function. If you write an LL class and create an equivalent input, you should get an equivalent output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.