Here is implementation for singly linkedlist. Any suggestions are most welcome
package linkedlist;
import java.util.Scanner;
public class linkedlist {
private int size=0;
private Node newNode,oldNode,firstNode,displayNode;
public void createNode(String value) {
if(size==0) {
newNode=new Node(value,null);
firstNode=newNode;
size++;
}
else {
oldNode=newNode;
newNode=new Node(value,null);
oldNode.setNextNode(newNode);
size++;
}
}
public void DisplayLinklist() {
displayNode=firstNode;
while(true) {
System.out.println(displayNode.getItem());
displayNode=displayNode.next;
if(displayNode.next==null) {
System.out.println(displayNode.getItem());
break;
}
}
}
private class Node{
private String item;
private Node next;
Node(String item,Node next){
this.item=item;
this.next=next;
}
public String getItem() {
return this.item;
}
public void setNextNode(Node address) {
this.next=address;
}
}
public static void main(String[] args) {
linkedlist mylinklist=new linkedlist();
Scanner in=new Scanner(System.in);
System.out.println("Enter the string value you want to save or press 'n'");
String input=in.next();
while(!input.equalsIgnoreCase("n")) {
mylinklist.createNode(input);
System.out.println("Enter the string value you want to save or press 'n'");
input=in.next();
}
mylinklist.DisplayLinklist();
}
}
This is very basic version and first time I am doing Linkedlist
. I am not using any iteration, but just wanted to confirm am I on the right path?