Reverse a singly linked list.

/*
Definition for singly-linked list.

public class ListNode {
  int val;
  ListNode next;
  ListNode(int x) { val = x; }
}
*/

public class Solution {
  public ListNode reverseList(
    ListNode head) {
  
  }
}

This problem is selected from LeetCode.

Solution

To reverse a singly linked list, we need to traverse the list and use 3 pointers to keep track of the previous, current and next node. Be aware of the boundary situation.

public class Solution {
  public ListNode reverseList(
    ListNode head) {

    if(head==null) return null;
    
    ListNode lastNode = head;
    ListNode nextNode = head.next;
    ListNode currentNode = null;

    while(nextNode != null) {
        currentNode = nextNode;
        nextNode = nextNode.next;
        currentNode.next = lastNode;
        lastNode = currentNode;
    }
    head.next = null;
    
    return lastNode;
  }
}

RelatedPost