As a linked list data structure learner, I'm practicing Leetcode problem "Reverse Linked List", I have my own solution but don't know why it was wrong, could anyone expert share some guidance on it? Really appreciate it!
Leetcode Question:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
My code:
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
while head:
temp = head
temp.next = prev
head = head.next
prev = temp
return prev
However, the above solution is wrong but can be corrected by switching the position between "temp.next = prev" and "head = head.next" as follows:
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
while head:
temp = head
head = head.next
temp.next = prev
prev = temp
return prev
For me, there is no difference between switching the two statements or not, how come they are different?