Reverse a singly linked lc-list.
Maintain prev, curr, and next. Iteratively reverse the next pointer of each node until the lc-list is reversed.
prev
curr
next
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; }
Recursively reverse the rest of the list, then set head.next.next = head and head.next = null to reverse the current edge.
head.next.next = head
head.next = null
public ListNode reverseListRecursive(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = reverseListRecursive(head.next); head.next.next = head; head.next = null; return newHead; }