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?

Asked By: Hume

||

Answers:

You already wrote the answer yourself:

cur = 3
    At the third while loop
cur.next = 2,
Answered By: Kelly Bundy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.