← Linked Lists

Reverse Linked List

Easy
Python
def reverse_list(head):
    prev=None
    while head:
        nxt=head.next; head.next=prev; prev=head; head=nxt
    return prev
Java
public ListNode reverseList(ListNode head){
    ListNode prev=null;
    while(head!=null){
        ListNode nxt=head.next; head.next=prev; prev=head; head=nxt;
    } return prev;
}

Key Insight

None is falsy — 'while head' is clean.

Python → Java Differences

  • None vs null
  • while head vs while!=null
  • Pointer reversal identical
Python
def reverse_list(head):
    prev=None
    while head:
        nxt=head.next; head.next=prev; prev=head; head=nxt
    return prev
Java
public ListNode reverseList(ListNode head){
    ListNode prev=null;
    while(head!=null){
        ListNode nxt=head.next; head.next=prev; prev=head; head=nxt;
    } return prev;
}

Algorithm Steps

1. Reverse pointer
2. Advance both