Answers for "revese the linked list java"

3

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;
}
Posted by: Guest on May-26-2020
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
Posted by: Guest on August-05-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language