206. reverse-linked-list

seokjeon

Se-ok Jeon

Posted on October 1, 2024

206. reverse-linked-list

Constraints

  1. The number of nodes in the list is the range [0, 5000].
  2. -5000 <= Node.val <= 5000

Idea #1 (Time: N^2, Memory: N)

  1. until End of List 1.1. pop 1.2. appendleft

Idea #2 (Time: N^2, Memory: N)

  1. until End of List 1.1. popleft 1.2. append

Test Cases

Example 1

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

Example 2

Input: head = [1,2]
Output: [2,1]

Example 3

Input: head = []
Output: []

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class LinkedList:
    def __init__(self, head=None):
        self.head = head
    def reverse(self):
        if self.head == None or self.head.next == None:
            return
        prev = None
        ahead = self.head.next
        while ahead:
            self.head.next = prev
            prev = self.head
            self.head = ahead
            ahead = ahead.next
        self.head.next = prev
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        linkedlist = LinkedList(head)
        linkedlist.reverse()
        return linkedlist.head
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
seokjeon
Se-ok Jeon

Posted on October 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related