Linked List User Input - java

I am trying to make a linked list which will take input from user that how many number he wants to make the linked list not using the built in LinkedList function. but if the user input a negative number it will give message the user to input a positive number. I have done the code for user input but finding very difficulty for other parts-negative input and linking the numbers.can anyone please give me these parts of codes.
import java.io.*;
import java.util.Scanner;
class MyList{
public MyList firstLink,lastLink;
int info,size;
MyList link;
private MyList next;
MyList(){
this.link=null;
firstLink = null;
lastLink=null;
}
public boolean isEmpty(){
return(firstLink == null);
}
public void showMyList() {
MyList currentLink = firstLink;
System.out.print("List: ");
while(currentLink != null) {
currentLink.showMyList();
currentLink = currentLink.lastLink;
}
System.out.println("");
}
}
public class MyLinkedList {
public static void main(String[] args){
MyList newMyList=new MyList();
Scanner userInput= new Scanner(System.in);
int userInputNumber;
System.out.println("Enter Total Data");
userInputNumber = userInput.nextInt();
int i=1;
while(i<=userInputNumber){
System.out.println("Enter Data "+ i +":");
i++;
newMyList.info=userInput.nextInt();
}
if(newMyList.firstLink!=null){
newMyList=newMyList.firstLink;
newMyList=newMyList.lastLink;
newMyList.firstLink=newMyList.firstLink.link;
}
}
}

This could help you understand Linked Lists:
LinkedList in wikipedia
A LinkedList consists of Nodes. A node could look like this:
class Node {
Node previousNode, nextNode;
int value;
public Node getLastNode() {
// traverse nextNode till it is null.. return the Node before.
}
}
Make a method for reading the user input, which returns the number entered.
private int getUserInput() {
int result = -1;
Scanner userInput= new Scanner(System.in);
while ( result < 0) {
result = userInput.nextInt();
}
return result;
}
After that you can create your LinkedList by creating Nodes as much as needed.
Node myLinkedList = new Node();
myLinkedList.value = 0;
for (int i = 1; i < getUserInputResult; i++) {
var newNode = new Node();
newNode.value = i;
// concat new Node to last Node in List;
var lastNodeInList = myLinkedList.getLastNode();
lastNodeInList .NextNode = newNode;
newNode.previousNode = lastNodeInList;
}

Related

Deleting N nodes after M nodes in a Singly Linked List

Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list
This is the Java program I wrote to solve this problem. For certain large test cases it's showing error,
"Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "" is null
at SinglyLinkedList.deleteNNodesAfterEveryMNodes(DeleteNNodesAfterMNodesOfALinkedList.java:88)
at DeleteNNodesAfterMNodesOfALinkedList.main(DeleteNNodesAfterMNodesOfALinkedList.java:127)"
import java.io.*;
import java.util.*;
class Link
{
public int data;
public Link next;
public Link(int d)
{
data = d;
}
public void displayLink()
{
System.out.print(data + " ");
}
}
class SinglyLinkedList
{
public Link first;
public SinglyLinkedList()
{
first = null;
}
public boolean isEmpty()
{
return(first == null);
}
public void insertLast(int d)
{
Link nl = new Link(d);
if(isEmpty())
{
first = nl;
}
else
{
Link curr = first;
while(curr.next != null)
{
curr = curr.next;
}
curr.next = nl;
}
}
public void displayList()
{
Link curr = first;
while(curr != null)
{
curr.displayLink();
curr = curr.next;
}
}
public void deleteNNodesAfterEveryMNodes(int N, int M)
{
Link curr1=first, curr2=first;
int n=N+M, m=M;
while(curr1!=null && curr1.next!=null)
{
while(curr2!=null && n!=0)
{
if(m != 1)
{
curr1 = curr1.next;
m--;
}
curr2 = curr2.next;
n--;
}
curr1.next = curr2;
m = M;
n = N+M;
curr1 = curr2;
}
}
}
class DeleteNNodesAfterMNodesOfALinkedList
{
public static void main(String st[])
{
Scanner sc = new Scanner(System.in);
SinglyLinkedList sll = new SinglyLinkedList();
int count, d, N, M;
System.out.println("Enter the number of integers you want to store in the singly linked list: ");
count = sc.nextInt();
System.out.println("\nEnter the " + count + " integers: ");
for(int i=0; i<count; i++)
{
d = sc.nextInt();
sll.insertLast(d);
}
System.out.println("\nThe singly linked list is: ");
sll.displayList();
System.out.println("\n\nEnter the value of 'M', the number of nodes to be skipped: ");
M = sc.nextInt();
System.out.println("\nEnter the value of 'N', the number of nodes now to be deleted: ");
N = sc.nextInt();
sll.deleteNNodesAfterEveryMNodes(N, M);
System.out.println("\nThe resultant singly linked list is: ");
sll.displayList();
}
}
I can't figure out what went wrong and how is assigning curr1.next = curr2; is of any issue at line 127
You can either try to put an additional check of curr1!=null in the second while loop or simplify the problem.
Simplifying the problem can be done by:
Using a for loop (m number of times) to traverse the list.
Using another for loop (n number of times) to call a piece of code that deletes the nodes one by one.
Also check for edge conditions i.e. if m + n < size and so on.

Java LinkedList on displaying Data

I have created an inventory management app where the user will be able to add, view and delete data from the inventory. When the user type A, the program will prompt user to enter data. If the user type D, the program will display the data in the inventory. I use LinkedList to achieve this. Im quite new to this. I was able to prompt user to enter data but was not able to display it. Theres a red line on the code. Where did I went wrong? I am sorry if the way I ask is wrong. Do correct me.
Main.java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = 0;
LinkedList myList = new LinkedList();
while(t != 1)
{
System.out.print("I, A, D");
char input = sc.next().charAt(0);
if(input == 'A')
{
System.out.print("Please enter item id: ");
int id = sc.nextInt();
sc.nextLine();
System.out.print("Please enter item name: ");
String name = sc.nextLine();
System.out.print("Please enter item type: ");
String type = sc.nextLine();
System.out.print("Please enter item price: ");
double price = sc.nextDouble();
sc.nextLine();
Item I1 = new Item(id, name, type, price);
myList.addItemToFront(I1);
}
else if(input == 'D')
{
myList.DisplayItem(); //at this point, theres red line which i dont know why?
}
}
LinkedList.java
class LinkedList {
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
newNode.setLink(head);
head = newNode;
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getLink();
count--;
}
}
public void addItemToFront(Item I1)
{
Node itemNode = new Node(I1);
itemNode.setLink(head);
head = itemNode;
}
public void DisplayItem(Node head)
{
if(head == null)
{
return;
}
Node current = head;
while (current != null)
{
System.out.println(current.data.toString());
current = current.getLink();
}
System.out.println(current);
}
public int length(Node head)
{
if(head == null)
{
return 0;
}
int count = 0;
Node current = head;
while(current != null)
{
count++;
current = current.getLink();
}
return count;
}
Node.java
public class Node {
Object data;
private Node link;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public Node(Object data) {
this.data = data;
this.link = null;
}
}
Sample output (How the program should run example)
I, A, D
A
Please enter item id: 001
Please enter item name: Wooden Chair
Please enter item type: Furniture
Please enter item price: 50.30
I, A, D
D
001, Wooden Chair, Furniture, 50.30
public void DisplayItem() {
if (head == null) {
return;
}
Node current = head;
while (current != null) {
System.out.println(current.getNodeItem().toString());
current = current.getLink();
}
}
Use this method
As I see your delete method in LinkedList.java class is expecting the Node head to be passed to it before it can iterate. You need to pass the head node to your display method then. I would expect it to be a Compiler error in your Main.java if you have put the right code above.
The display method in your linked list class accepts an argument of type node which is the head. you need to pass that argument from the main method, then it will work.
Instead of : myList.DisplayItem();
Do this : myList.DisplayItem(head);
Now, if we llok at your LinkedList class, you have made the 'head' as a private variable, either make it public, so that you can access it from the Main class or you can remove the argument from the DisplayItem(Node head) method because any ways you are using the head as a global variable and then iterating over it in the DisplayItem method.
So, better remove the argument from the method definition, it will work.

Why does reversing my linkedlist not work as expected?

Below is linked list program, I am trying to reverse the linked list by k- nodes. k is the input provided by the user. But the issue is below logic only returns first three nodes in reverse order.
package p;
import java.util.Scanner;
public class LinkedListDemoReverseKNode {
class MyList {
public int info;
public MyList link;
public MyList(){
this.link = null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyList s = new MyList();
System.out.println("enter value :");
s.info = sc.nextInt();
Character ch = null;
MyList t = s;
MyList commonNode = null;
while (true) {
System.out.println("to create node press Y else N ");
ch = sc.next().charAt(0);
if (ch == 'n' || ch == 'N') {
break;
}
s.link = new MyList();
System.out.println("enter value for the node :");
s.link.info = sc.nextInt();
s = s.link;
}
// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
}
}
private MyList reverseLinkedListKNode(MyList head, int k) {
MyList s = head;
MyList prev = null;
MyList next = null;
int count = 0;
while (count < k && s != null) {
next = s.link;
s.link = prev;
prev = s;
s = next;
count++;
}
if (next != null)
s.link = reverseLinkedListKNode(next, k);
return prev;
}
}
// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
In this line of code where it says:
MyList head = linkedlistDemo3.reverselinkedlistNode(s,3)
Try changing where it says (s, 3)
If you look at this part of your code MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3); you are telling it to reverse the three first nodes in your linked list.
The method asks for number of k nodes to be reversed:
private MyList reverseLinkedListKNode(MyList head, int k)
You could set k to the total nodes in the list to reverse all nodes, or to any number of nodes to reverse.
Good luck.
You can simply use Collections.reverse...

LinkedList isn't taking input

I seem to be having some problems with inserting values into a linked list. I am trying to create a program for the Josephus problem and I am suppose to take 3 numbers from the user. The first number is how many "people" there are, say its 4 you would have a list of 1,2,3,4. This is where I am stuck. Every time I enter in the 3 ints my program returns saying the List is empty and I can't figure out why. If anyone could help explain it would be greatly appreciated, thanks!
Main
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
long[] numbers = new long[3];
LinkedList circle = new LinkedList();
System.out.println("Please enter 3 numbers");
for (int i = 0; i < 3; i++)
{
numbers[i] = input.nextLong();
}
for (int i = 0; i < numbers[0]; i++)
{
circle.insertLink();
circle.move();
}
circle.getCurrent();
}
Link
class Link
{
public long dData;
public Link next;
public Link(long dd)
{
dData = dd;
}
public Link(int d, Link n)
{
this(d);
next = n;
}
public void displayLink()
{
System.out.print(dData + " ");
}
}
Linked List
class LinkedList
{
private Link current;
private int id;
public LinkedList()
{
current = null;
id = 1;
}
public void move()
{
current = current.next;
}
public boolean isEmpty()
{
if(current == null)
System.out.println("The List is empty");
return current == null;
}
public Link getCurrent()
{
return current;
}
public void setCurrent(int id)
{
while(current.dData != id)
move();
}
public Link getNext()
{
return current.next;
}
public void insertLink()
{
if(!isEmpty())
{
Link newlink = new Link(id++, current.next);
current.next = newlink;
}
else
{
Link newlink = new Link(id++);
newlink.next = newlink;
current = newlink;
}
}
public Link deleteLink()
{
Link temp = current.next;
if(current != current.next)
current.next = current.next.next;
else
current = null;
return temp;
}
}
when first time you call insertLink() methos you always will get The List is empty print. because at initialization the current variable of your linked list class is null. just remove System.out.println("The List is empty"); from your code.
public boolean isEmpty()
{
return current == null;
}
override toString() method to see your list
You are taking three inputs from user and iterating with first element of numbers array, i think it should be
for (int i = 0; i < numbers.length; i++)
{
circle.insertLink();
circle.move();
}
And at the first time when you insert the link, isEmpty() method checks your current variable is null or not if it is then it print the "The list is empty". so just remove that line.
System.out.println("The List is empty");

How to implement Search Function using Singly Linked List in Java?

Hello fellow Programmers!
I would like to ask how to implement the Search Function in Singly Linked List using Java (Data Structures).
PROBLEM: The Search function of my program can only access the head and tail of the elements.
Question: How can I access all the elements?
Sample Code:
import java.util.*;
public class MyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
if(head == null){
head = nd;
tail = nd;
}
else {
tail.setNextRef(nd);
tail = nd;
}}
public void delete(){
if(head == null){
System.out.println("List is empty...");
}
else{
Node<T> tmp = head;
head = tmp.getNextRef();
if(head == null){
tail = null;
}
System.out.println("Deleted: "+tmp.getValue());
System.out.println("First Employee Name Deleted!");
}
}
public void search(){
Node<T> tmp = head;
if(head==null){
System.out.println("List is empty...");
}
else{
String b=""+tmp.getValue();
Scanner input=new Scanner(System.in);
System.out.print("Enter an employee name to search: ");
String search = input.nextLine();
if(b.equals(search)){
System.out.println("Found! "+tmp.getValue());
}
else if (b!=search){
System.out.println("Not Found!");
}
tmp = tmp.getNextRef();
} }
public void show(){
Node<T> tmp = head;
if(head==null){
System.out.println("List is empty...");
}
else{
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue());
tmp = tmp.getNextRef();
}}
}
public static void main(String a[]){
MyLinkedList<String> sl = new MyLinkedList<String>();
Scanner input = new Scanner(System.in);
sl.add("Garcia, Bianca Axel, 001");
sl.add("Temprosa, Camille Ann, 002");
sl.add("Villanueva, Von Justin, 003");
sl.add("Rivera, Reygie, 004");
sl.add("Dapapac, Ronnelle, 005");
sl.add("Bati, Aubrey, 006");
sl.add("Fiestada, Diana Rose, 007");
sl.add("Dobalada, Jojo, 008");
sl.add("Del Mundo, Maria Ethel, 009");
sl.add("Alejandro, Rachelle, 010");
System.out.print("Welcome To Singly Linked List Management for Employee Names!\n(Created by: Alex del Rosario || Source Code: Mr. John Carlo Son)\n");
while(true){
System.out.println("*------------------------*");
System.out.println("*PLEASE SELECT A FUNCTION*");
System.out.println("*1.)Add Employee Name *");
System.out.println("*2.)Delete Employee Name *");
System.out.println("*3.)Show Employee List *");
System.out.println("*4.)Search an Employee *");
System.out.println("*5.)Exit the program *");
System.out.println("*------------------------*");
System.out.print("Enter a number: ");
int select = input.nextInt();
if(select==1){
System.out.println("**Enter an employee name with ID number**");
System.out.println("Use this format:(Last Name),(First Name),(ID number)");
System.out.println("(ex. del Rosario, Alex, 0001)");
System.out.print("Input here: ");
input.nextLine();
String employee=input.nextLine();
sl.add(employee);
System.out.println("Employee: "+employee+" successfully added!");
}
else if(select==2){
sl.delete();
}
else if(select==3){
System.out.println("Employee List:");
sl.show();
}
else if(select==4){
sl.search();
}
else if(select==5){
System.out.println("*** THANK YOU FOR USING THIS PROGRAM! :) ***");
System.exit(0);
}
else{
System.out.println("INVALID INPUT!");
}
}}
}
class Node <T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> ref) {
this.nextRef = ref;
}
#Override
public int compareTo(T arg) {
if(arg == this.value){
return 0;
} else {
return 1;
}
}
}
More a tipp than an answer. Ask yourself what you want to do. Do you want to use the linked list provided by Java or write your own code for a linked list?
With the provided list iterating is easy.
private void search(String searchElement) {
for (int i = 0; i < list.size(); i++) {
String listElement = list.get(i);
if (searchElement.equals(listElement)) {
System.out.println("Found element " + searchElement + " at position " + i);
return;
}
}
System.out.println(searchElement + " does not appear in the list");
}
When writing your own list you have to be more careful how you use the list. For example your implementation of delete() will not work.
public void delete(){
if(head == null){
System.out.println(List is empty...);
}
else{
NodeAlex tmp = head;
head = tmp.getNextRef();
if(head == null){ // you need to check if head == tail or head.getNextRef() == null
tail = null; // here you have to set tmp.setNextRef(null);
// and additionally define tmp as tail.
}
System.out.println(Deleted +tmp.getValue());
System.out.println(First Employee Name Deleted!);
}
}
Edit: To access the list you have two possibilities. At first you have to create a new instance, i.e., (here for Strings, you might want to use other types/objects)
List<String> list = new LinkedList<String>();
Then you basically have two opportunities on how to access the list in the methods.
(a) Your method is in the same class where you initialized the list, however, list has to be a global field.
private List<String> list;
private static void main(String[] args) {
list = new LinkedList<String>();
(...)
}
private static void search(String searchElement) {
// has access on list
}
(b) You simply pass your list to the method you need and if the method modifies the list you need to return the list again.
(main class, main method)
search(list, "Test");
list = delete(list, "Test");
(the class where the methods are located)
public void search(List<String> list, String searchElement) { ... }
public List<String> delete(List<String> list, String elementToDelete) {
// delete element
return list;
}

Categories