Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
import java.util.LinkedList;
import java.util.Scanner;
class Node
{
    int data;
    Node next;
 
    Node(int data, Node next)
    {
        this.data = data;
        this.next = next;
    }
}
 
public class Main
{
    // Helper function to print a given linked list
    public static void printList(Node head)
    {
        Node ptr = head;
        while (ptr != null)
        {
            System.out.print(ptr.data + " ");
            ptr = ptr.next;
        }
    }
 
    // Reverses a given linked list by changing its `.next` fields and
    // its head.
    public static Node reverse(Node head)
    {
        Node previous = null;
        Node current = head;
 
        // traverse the list
        while (current != null)
        {
            // tricky: note the next node
            Node next = current.next;
 
            // fix the current node
            current.next = previous;   
            
            previous = current;
            current = next;
        }
 
        // fix the head to point to the new front
        return previous;
    }
 
    public static void main(String[] args)
    {
    	LinkedList list = new LinkedList();
    	
    	Scanner sc = new Scanner(System.in);
    	
        System.out.print("Input the number of nodes: ");
        int size = sc.nextInt();
    	
    	System.out.print("Please input data for node: ");
        int keys[] = new int[size];
        for(int i = 0; i < size; i++)
        {
        	keys[i] = sc.nextInt();
        	
        }
 
        Node head = null;
        for (int i = size - 1; i >= 0; i--) 
        {
            head = new Node(keys[i], head);
        }
 
        head = reverse(head);
        printList(head);
    }
}


What I have tried:

I think im not using the linked list
and I want to save a user input into the linked list
like if he inputs 3 nodes
then he will input a number to
node 1 = 5
node 2 = 6
node 3 = 7

and the output will be a reverse which i already done in my code

I just want it to print out like this

Input the number of nodes : 3

Input data for node 1 : 5
Input data for node 2 : 6
Input data for node 3 : 7

Data entered in the list are : 5 6 7

The list in reverse are : 7 6 5
Posted
Comments
Richard MacCutchan 15-Sep-21 4:01am    
For a singly linked list, each node should point to the next one. The last node's pointer should be null. It is not clear what the problem is with your code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900