No206. Reverse Linked List
topic
Reverse a singly linked list.
Example
- Input: 1->2->3->4->5->NULL
- Output: 5->4->3->2->1->NULL
Advanced
You can reverse the linked list iteratively or recursively. Can you solve this problem in two ways?
Idea 1
- The first traversal, save the data;
- The second traverse, change the data;
Problem-solving code (Python3)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
result = []
p = head
while p:
result.append(p.val)
p = p.next
p = head
i = 0
while p:
p.val = result[-1-i]
i += 1
p = p.next
return head
Complexity analysis:
- Time complexity O(n)
- Space complexity O(n) requires additional space to store elements
operation result
Idea 2
Iterate, construct a two-way list of classes to change the direction of the pointer to achieve the goal:
- Use pNext to store the next node of the current node
- Change head.next to prev, prev to head, and head to pNext
Problem-solving code (Python3)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
while head:
pNext = head.next
head.next,prev,head = prev,head,pNext
return prev
Complexity analysis
- Time complexity O(n)
- Space complexity O(1)