Q1 Reverse a linked list | Practice | GeeksforGeeks

PHOTO EMBED

Thu Jan 05 2023 19:25:09 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

//{ Driver Code Starts
import java.util.*;
import java.io.*;

class Node{
    int data;
    Node next;
    
    Node(int x){
        data = x;
        next = null;
    }
    
}
class GFG{
	static void printList(Node node) 
	{ 
		while (node != null) 
		{ 
			System.out.print(node.data + " "); 
			node = node.next; 
		} 
		System.out.println(); 
	}
    public static void main(String args[]) throws IOException { 
        
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        
        while(t > 0){
        
        	int n = sc.nextInt();
        
            Node head = new Node(sc.nextInt());
            Node tail = head;
        
            for(int i=0; i<n-1; i++)
            {
                tail.next = new Node(sc.nextInt());
                tail = tail.next;
            }
        
            Solution ob = new Solution();
            head = ob.reverseList(head);
            printList(head); 
            t--;
        }
    } 
} 
   
// } Driver Code Ends


//function Template for Java

/* linked list node class:

class Node {
    int value;
    Node next;
    Node(int value) {
        this.value = value;
    }
}

*/

class Solution
{
    //Function to reverse a linked list.
    Node reverseList(Node head)
    {
        Node prev = null;
        Node next = null;
        Node current = head;
        
        
        while(current != null){
            next = current.next;
            current.next = prev ;
            
            prev = current;
            current = next;
        }
        return prev;
    }
}

content_copyCOPY

https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1