[LeetCode]#206. Reverse Linked List

Fatboy Slim
Jul 26, 2021

Environment: Python 3.8

Key technique: List node

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Analysis:

  1. Use below four steps to revise link.
  2. temp=head
  3. head=head.next
  4. temp.next=ans
  5. ans=temp

Solution:

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = [1,2,3]
head=ListNode(1)
head.next=ListNode(2)
head.next.next=ListNode(3)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
ans = None
while head:
temp = head
head = head.next
temp.next = ans
ans = temp
return ans

Submissions:

Reference:

https://leetcode.com/problems/reverse-linked-list/discuss/1352989/Python-O(n)-time-O(1)-space

--

--