reverse a linke dlist in java code example

Example 1: reverse linked list in java to get both head and tail

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

public static ListNode[] reverse_linked_list(ListNode head) {

        ListNode prev = null;
        ListNode current = head;
        ListNode next;

        ListNode tail = head;

        while (current != null) {

            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        head = prev;

        ListNode[] result = {head, tail};

        return result;
}

Example 2: revese the linked list java

Easiest way


public static LinkedList reverse(LinkedList head) {
		LinkedList prevAddress = null;
		LinkedList currentAddress = head;
		LinkedList nextAddress = head.next;
		
		while(nextAddress!=null) {
			currentAddress.next = prevAddress;
			prevAddress = currentAddress;
			currentAddress = nextAddress;
			nextAddress= currentAddress.next;
			currentAddress.next = prevAddress;
		}
		head = currentAddress;
		return head;
	}
    
Just try to visualize its all about pointers game. :-)
  NO GFG ANSWER

Tags: