Data Structures & Algorithms View on GitHub โ†—

Reverse A Linked List

Java

/**
 * Definition for singly-linked list.
 * 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) {
        if (head == null)
            return null;
        
        ListNode prev = null, curr = head;

        while(curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }

        return prev;
    }
}

Python

# Definition for singly-linked list.
# 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]:
        if not head:
            return None

        newhead = head

        if head.next:
            newhead = self.reverseList(head.next)
            head.next.next = head

        head.next = None

        return newhead

Enjoyed this solution?

I write about software engineering, algorithms, and lessons learned. Check out more in the newsletter.

Browse the newsletter