File: Node.java
package org.developersbrain.solutions;
//Linked List implementation using Recursive methods
//This is a generic implementation
public class Node<T> {
Node<T> nextNode;
T t;
Node(T t){
this.t = t;
nextNode=null;
}
public Node<T> insertRear(Node<T> next){
if(next.nextNode!=null) {
next=insertRear(next.nextNode);
}
return next;
}
public void insert(T t){
Node<T> newN=new Node<T>(t);
Node<T> lastNode=insertRear(this);
//Looped through all elements to find the last element
//Because the insert is always at the end in the singly linked list
lastNode.nextNode=newN;
}
private Node<T> printNode(Node<T> node){
if(node != null){
System.out.println(node.t.toString());
//You have to overwrite the generic original class for the method to_string
//to print the output as the way you want
node=printNode(node.nextNode);
}
return node;
}
public void traverse(){
printNode(this);
}
}
package org.developersbrain.solutions;
//Linked List implementation using Recursive methods
//This is a generic implementation
public class Node<T> {
Node<T> nextNode;
T t;
Node(T t){
this.t = t;
nextNode=null;
}
public Node<T> insertRear(Node<T> next){
if(next.nextNode!=null) {
next=insertRear(next.nextNode);
}
return next;
}
public void insert(T t){
Node<T> newN=new Node<T>(t);
Node<T> lastNode=insertRear(this);
//Looped through all elements to find the last element
//Because the insert is always at the end in the singly linked list
lastNode.nextNode=newN;
}
private Node<T> printNode(Node<T> node){
if(node != null){
System.out.println(node.t.toString());
//You have to overwrite the generic original class for the method to_string
//to print the output as the way you want
node=printNode(node.nextNode);
}
return node;
}
public void traverse(){
printNode(this);
}
}
File : MainClass.java
package org.developersbrain.solutions;
public class MainClass {
public static void main(String[] args){
Node<Integer> ll=new Node<Integer>(5);
ll.insert(10);
ll.insert(20);
ll.insert(30);
System.out.println("List Traversing- Integer");
System.out.println("----------------");
ll.traverse();
Node<String> ll_Names=new Node<String>("Name 1");
ll_Names.insert("Name 2");
ll_Names.insert("Name 3");
ll_Names.insert("Name 4");
System.out.println("List Traversing - String");
System.out.println("----------------");
ll_Names.traverse();
Node<Double> ll_dbl=new Node<Double>(10.23);
ll_dbl.insert(11.23);
ll_dbl.insert(12.2323);
ll_dbl.insert(34.33);
System.out.println("List Traversing- Double Values");
System.out.println("----------------");
ll_dbl.traverse();
}
}
output:
--------------------------------------------
List Traversing- Integer
----------------
5
10
20
30
List Traversing - String
----------------
Name 1
Name 2
Name 3
Name 4
List Traversing- Double Values
----------------
10.23
11.23
12.2323
34.33
Comments
Post a Comment