LeetCode Python/Java/C++/JS  >  Linked List  >  206. Reverse Linked List  >  Solved in Java, Python, C++, JavaScript, C#, Go, Ruby  >  GitHub or Repost

LeetCode link: 206. Reverse Linked List, difficulty: Easy.

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]

Example 2:

Input: [1,2]

Output: [2,1]

Example 3:

Input: []

Output: []

Constraints:

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

Intuition

Webmaster (Zhang Jian): πŸ‘‹

Hi everyone! I am Zhang Jian.
I know the challenge of transitioning from mastering algorithms to actually landing a great job. That's why, in addition to this resource, I personally developed leader.me!

πŸš€ leader.me is the ultimate all-in-one platform for programmers to build their personal brand, featuring portfolio hosting, resume builders, and integrated blogs.

Build your programmer brand at leader.me β†’


  1. To solve this problem, we only need to define two variables: current and previous. How do we inverse two node?

    Click to view the answer

    current.next = previous is the inversion.

  2. Which should be the loop condition? while (current != null) or while (current.next != null)?

    Click to view the answer

    It is while (current != null), because the operation to be performed is current.next = previous.

Step-by-Step Solution

  1. Traverse all nodes.

    previous = null
    current = head
    
    while (current != null) {
        current = current.next
    }
    
  2. Add current.next = previous.

    previous = null
    current = head
    
    while (current != null) {
        tempNext = current.next
        current.next = previous
        current = tempNext
    }
    
  3. Currently previous is always null, we need to change it: previous = current.

    previous = null
    current = head
    
    while (current != null) {
        tempNext = current.next
        current.next = previous
        previous = current
        current = tempNext
    }
    

Complexity

Time complexity

O(N)

Space complexity

O(1)

Java #

/**
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode previous = null;
        var current = head;

        while (current != null) {
            var tempNext = current.next;
            current.next = previous;
            previous = current;
            current = tempNext;
        }

        return previous;
    }
}

Python #

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        previous = None
        current = head

        while current:
            temp_next = current.next
            current.next = previous
            previous = current
            current = temp_next

        return previous

C++ #

/**
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* previous = nullptr;
        ListNode* current = head;

        while (current) {
            auto temp_next = current->next;
            current->next = previous;
            previous = current;
            current = temp_next;
        }

        return previous;
    }
};

JavaScript #

/**
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
var reverseList = function (head) {
  let previous = null
  let current = head

  while (current != null) {
    const tempNext = current.next
    current.next = previous
    previous = current
    current = tempNext
  }

  return previous
};

C# #

/**
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution
{
    public ListNode ReverseList(ListNode head)
    {
        ListNode previous = null;
        ListNode current = head;

        while (current != null)
        {
            var tempNext = current.next;
            current.next = previous;
            previous = current;
            current = tempNext;
        }

        return previous;
    }
}

Go #

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    var previous *ListNode
    current := head

    for current != nil {
        tempNext := current.Next
        current.Next = previous
        previous = current
        current = tempNext
    }

    return previous
}

Ruby #

# class ListNode
#     attr_accessor :val, :next
# 
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end

def reverse_list(head)
  previous = nil
  current = head

  while current
    temp_next = current.next
    current.next = previous
    previous = current
    current = temp_next
  end

  previous
end

Other languages

Welcome to contribute code to LeetCode.blog GitHub -> 206. Reverse Linked List. Thanks!

Level Up Your Developer Identity

πŸš€ While mastering algorithms is key, showcasing your talent is what gets you hired.
We recommend leader.me β€” the ultimate all-in-one personal branding platform for programmers.

The All-In-One Career Powerhouse:

  • πŸ“„ Resume, Portfolio & Blog: Integrate your skills, projects, and writing into one stunning site.
  • 🌐 Free Custom Domain: Bind your own personal domain for freeβ€”forever.
  • ✨ Premium Subdomains: Stand out with elite tech handle like name.leader.me.

Build Your Programmer Brand at leader.me β†’