Reverse LinkedList


Reverse Linked List

Solution (Traverse the linked list, pointing the next of each node to the previous node)

  1. Save the next of the current node, next = curr.next
  2. Point the next of the current node to the previous node, curr.next = prev
  3. Move the forward pointer back to prev = curr
  4. Move the current pointer back to curr = next

Step

1.Initial list and pre node

2.Initial list and next node, next = curr.next

3.The current.next points to the pre node, curr.next = prev

4.The pre node points to the current node, prev = curr

5.The current node points to the next node, curr = nex

6.The next node moves to the current.next, next = curr.next

7.Loop traversal

Code

package LinkedLists;

/**
 * @author zhengstars
 * @date 2023/08/19
 */
public class ReverseLinkedList {
    public static class ListNode {
        int value;
        ListNode next;

        public ListNode(int value) {
            this.value = value;
            this.next = null;
        }
    }

    public static ListNode reverseLinkedList(ListNode head) {
        ListNode prev = null;

        ListNode curr = head;

        ListNode next = null;

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

        }
        return prev;
    }
}



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • 2379. Minimum Recolors to Get K Consecutive Black Blocks
  • 2471. Minimum Number of Operations to Sort a Binary Tree by Level
  • 1387. Sort Integers by The Power Value
  • 2090. K Radius Subarray Averages
  • 2545. Sort the Students by Their Kth Score