Example: we have linked list1 → 2 → 3 → Ø, we would like to change it toØ ← 1 ← 2 ← 3.
Solution 1: brute force (traverse twice)
convert the linked list to a array, and then convert the array to a new linked list in another direction.
defreverseList(self,head):""" :type head: ListNode :rtype: ListNode """ifnot head:return head# brute force# convert to array res = [] pointer = headwhile pointer isnotNone: res.append(pointer.val) pointer = pointer.next# convert back to a new linked list ret =ListNode(res[0])for item in res[1:]: ret = self.helper(ret, item)return retdefhelper(self,head,num): ret =ListNode(num) ret.next = headreturn ret
Idea: reverse linked list when traverse each element (traverse once)
While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference.