Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

java reverse linked list

    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;
    }
Comment

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
Comment

How to efficiently reverse a singly linked list, in Java?


/*
	This is an implementation that shows how
	to reverse a singly linked list in place.
	Each linked list node has an integer value
	as well as a next pointer that points to 
	the next node or null in case of tail of list.
	
	Let n be the number of nodes in the list.
	Time complexity: O(n) 
	Space complexity: O(1)
*/

public class ReverseLinkedList {
	private ListNode head;

	public ReverseLinkedList() {
		/*
		 * Create below linked list
		 * 0 -> 1 -> 2 -> 3 -> 4 -> 5
		 */
		head = new ListNode(0, null);
		ListNode prev = head, temp;
		for (int i = 1; i <= 5; i++) {
			temp = new ListNode(i, null);
			prev.next = temp;
			prev = temp;
		}
	}

	// Print elements of linked list starting from head
	private void printLinkedList() {
		ListNode temp = head;
		while (temp != null) {
			System.out.print(temp.val + " ");
			temp = temp.next;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		ReverseLinkedList application = new ReverseLinkedList();
		application.printLinkedList(); // 0 1 2 3 4 5
		application.reverseList();
		application.printLinkedList(); // 5 4 3 2 1 0
	}

	public void reverseList() {
		if (head == null || head.next == null) {
			return;
		}

		// Three pointers are used to allow for
		// efficient reversal of the list
		ListNode previousNode = null;
		ListNode currentNode = head;
		ListNode nextNode;

		while (currentNode != null) {
			// Keep updating next, current, and
			// previous pointers properly until
			// end of list is reached.
			nextNode = currentNode.next;
			currentNode.next = previousNode;
			previousNode = currentNode;
			currentNode = nextNode;
		}
		// List has a new head
		head = previousNode;
	}

	// Class representing a linked list node
	// with pointers to value and next node

	private class ListNode {
		int val;
		ListNode next;

		ListNode(int val, ListNode next) {
			this.val = val;
			this.next = next;
		}
	}
}
Comment

How to reverse linked list in java.

// Java program of the above approach
class GFG {
 
    // Create a class Node to enter values and address in the list
    static class node {
        int val;
        node next;
    };
 
    static node head = null;
    // code to count the no. of nodes
    static int count(node head)
    {
        node p = head;
        int k = 1;
        while (p != null) {
            p = p.next;
            k++;
        }
        return k;
    }
 
    // to reverse the linked list
    static node ll_reverse(node head)
    {
        node p = head;
        int i = count(head), j = 1;
        int[] arr = new int[i];
        while (i != 0 && p != null) {
            arr[j++] = p.val;
            p = p.next;
            i--;
        }
        j--;
        while (j != 0) // loop will break as soon as j=0
            System.out.print(arr[j--] + " ");
        return head;
    }
    // code to insert at end of ll
    static node insert_end(node head, int data)
    {
        node q = head;
        node p = new node();
        p.val = data;
        p.next = null;
        while (q.next != null)
            q = q.next;
        q.next = p;
        p.next = null;
        return head;
    }
 
    // create ll
    static node create_ll(node head, int data)
    {
        node p = new node();
        p.next = null;
        p.val = data;
        if (head == null) {
            head = p;
            p.next = null;
            return head;
        }
        else {
            head = insert_end(head, data);
            return head;
        }
    }
 
    public static void main(String[] args)
    {
        int i = 5, j = 1;
        while (i != 0) {
            head = create_ll(head, j++);
            i--;
        }
        head = ll_reverse(head);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
Comment

PREVIOUS NEXT
Code Example
Java :: android studio remove action bar 
Java :: read integer input java 
Java :: do while loop in java 
Java :: how to make int array java android 
Java :: How to efficiently find three largest numbers of array, in Java? 
Java :: java print hex format 
Java :: como calcular a raiz quadrada em java 
Java :: java generate random id 
Java :: Spring boot fix cors problem 
Java :: len of number in java 
Java :: android alertdialog setSingleChoiceItems 
Java :: key listener java 
Java :: java remainder sign 
Java :: byte array to base64 string 
Java :: java check two dates same day 
Java :: clear jtable rows java 
Java :: recycler view implementation 
Java :: check whether a double is not a number in java 
Java :: How to close jframe on click of button 
Java :: android studio change title bar text 
Java :: java terminal colors 
Java :: in java how to throw exception from function 
Java :: try block in java 
Java :: thread 
Java :: string length solidity 
Java :: how to use deque as queue in java? 
Java :: android studio create a Uri 
Java :: pretty print json in console 
Java :: how to cast from int to string java 
Java :: iterate through hashMap by forEach loop 
ADD CONTENT
Topic
Content
Source link
Name
3+2 =