How to take input in linked list in java
import java.util.Scanner;
// Define a Node class
class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
// Define a LinkedList class
class LinkedList {
Node head;
public LinkedList(Node head) {
this.head = head;
}
public void append(int value) {
// Create a new node
Node newNode = new Node(value, null);
// Set the current node to the head
Node current = head;
// Find the last node in the list
if (current != null) {
while (current.next != null) {
current = current.next;
}
current.next = newNode;
} else {
head = newNode;
}
}
}
// Test the LinkedList class
LinkedList linkedList = new LinkedList(null);
Scanner scanner = new Scanner(System.in);
// Read in the values from the user
while (true) {
System.out.print("Enter a value (enter 'done' to finish): ");
String input = scanner.nextLine();
if (input.equals("done")) {
break;
}
linkedList.append(Integer.parseInt(input));
}
// Print the values of the nodes
Node node = linkedList.head;
while (node != null) {
System.out.println(node.value);
node = node.next;
}
This code creates a linked list in Java, which is a data structure that consists of nodes linked together in a sequence. The linked list is created using two classes: Node and LinkedList.
The Node class represents a single node in the linked list, and contains two fields: value, which stores the value of the node, and next, which is a reference to the next node in the list.
The LinkedList class represents the entire linked list, and contains a single field: head, which is a reference to the first node in the list.
The code first creates an empty linked list by passing null to the LinkedList constructor.
Then, it uses a Scanner object to read in values from the user. It does this by looping continuously and prompting the user to enter a value. If the user enters "done", the loop exits.
For each value entered by the user, the code creates a new Node object and appends it to the end of the linked list using the append method.
The append method finds the last node in the list by starting at the head and traversing the list until it reaches the end. It then sets the next field of the last node to the new node.
Finally, the code prints out the values of all the nodes in the linked list by starting at the head and traversing the list one node at a time, printing out the value of each node.
0 Comments
if you are not getting it then ask i am glad to help