Why does this reverse list python code return the reversed list?
Question:
def reverseList(self, head):
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
This is the python code which return the reverse order linked list like below.
Input: 1 -> 2 -> 3 -> Null
Output: 3 -> 2 -> 1 -> Null
The question is when I hand write the output with input, it comes out below process.
At the first while loop
cur.next = N,
prev = 1,
cur = 2
At the Second while loop
cur.next = 1,
prev = 2,
cur = 3
At the third while loop
cur.next = 2,
prev = 3,
cur = N
return 3
I guess it should return only 3, not 3 -> 2 -> 1-> Null. Why this code return the reverse order Linked list? Could anyone answer?
Answers:
You already wrote the answer yourself:
cur = 3
At the third while loop
cur.next = 2,
def reverseList(self, head):
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
This is the python code which return the reverse order linked list like below.
Input: 1 -> 2 -> 3 -> Null
Output: 3 -> 2 -> 1 -> Null
The question is when I hand write the output with input, it comes out below process.
At the first while loop
cur.next = N,
prev = 1,
cur = 2
At the Second while loop
cur.next = 1,
prev = 2,
cur = 3
At the third while loop
cur.next = 2,
prev = 3,
cur = N
return 3
I guess it should return only 3, not 3 -> 2 -> 1-> Null. Why this code return the reverse order Linked list? Could anyone answer?
You already wrote the answer yourself:
cur = 3
At the third while loop
cur.next = 2,