DEV Community

Se-ok Jeon
Se-ok Jeon

Posted on

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay