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) { if (head == null || head.next == null){ return head; } ListNode next = head.next; head.next = null; while (next.next != null){ ListNode node = next.next; next.next = head; head = next; next = node; } next.next = head; return next; } }