How to display elements in a Linked list by recursion? - java

Hello this is my linked list without implementing java.util.linkedlist
I'd like to create a method that display recursively all of the elements in my linked list but I have no idea how to, my method doesn't have any parameters so I don't know how to get to the next value when calling the method itself
public class Pokemon {
private String name;
private String type;
private int niveau;
public Pokemon(String name, String type) {
this.name = name;
this.type = type;
this.niveau = (int) (Math.random() * (1 * 1 - 100) + 100);
}
public void display() {
System.out.println(this.name);
}
public class Trainer {
public final String name;
private Pokeball head;
public Trainer(String name) {
this.name = name;
}
public void addPokemon(Pokemon pok) {
if (this.head != null) {
this.head.addPokemon(pok);
} else {
this.head = new Pokeball(pok);
}
}
public void display() {
if (this.head == null)
return;
else {
this.head.display();
}
}
public class Pokeball {
private Pokemon pok;
private Pokeball next;
public Pokeball(Pokemon pok) {
this.pok = pok;
}
public Pokeball(Pokemon pok, Pokeball next) {
this.pok = pok;
this.next = next;
}
public void addPokemon(Pokemon pok) {
Pokeball current = this;
while (current.next != null) {
current = current.next;
}
current.next = new Pokeball(pok);
}
public void display() {
Pokeball current = this;
if (current.next == null){
return;
} else {
// ....
}
}

I assume this is for Pokeballclass, Why you would like to display using recursion ? why not iteration? Your Trainer class doesn't create a linked list, it has no next.
public void display() {
Pokeball current = this; //Note that this won't change your 'this'
while ( current != null ) {
System.out.print( current.display() + "->" );
current = current.next;
}
}
Recursive:
private void display_recurse( Pokeball current ) {
if ( current == null )
return;
System.out.print( current.display() + "->" );
display_recurse( current.next);
}
You may call this like:
public void display() {
display_recurse( this );
}

Usually this is accomplished using a private helper function that does have a parameter.
public void display() {
Pokeball current = this;
display(current);
}
private void display(Pokeball toDisplay) {
if(toDisplay == null) {
return;
} else {
// code to display current here
// ...
display(toDisplay.next);
}
}

Related

Inserting an integer into a regular binary tree

While revising for my final, I came across binary trees (regular ones). After going through the lecture, I started to solve previous labs.
My problem here is that only 6 is inserted into the tree. What is wrong with my method?
What I'm trying to input:
tree.insert(1); tree.insert(15); tree.insert(7);
tree.insert(13); tree.insert(58); tree.insert(6);
The Node class:
public class Node {
public int key;
public Node left_child;
public Node right_child;
// The Constructor(s).
public Node() {
}
public Node(int key) {
this.key = key;
left_child = null;
right_child = null;
}
// The Get Methods.
public int getKey() {
return key;
}
public Node getLeft_child() {
return left_child;
}
public Node getRight_child() {
return right_child;
}
// The Set Methods.
public void setKey(int key) {
this.key = key;
}
public void setLeft_child(Node left_child) {
this.left_child = left_child;
}
public void setRight_child(Node right_child) {
this.right_child = right_child;
}
}
The BinaryTree class:
public class BinaryTree {
private Node root;
// The Constructor Method(s)
public BinaryTree() {
root = null;
}
public boolean is_empty() {
return (root == null);
}
public void insert(int k) {
insert(root, k);
}
private Node insert(Node x, int k) {
Node p = new Node(k);
if (x == null) {
root = p;
}
else {
if (x.left_child != null) {
insert(x.left_child, k);
}
else {
insert(x.right_child, k);
}
}
return x;
}
// Printing Method(s).
public void print_inorder() {
print_inorder(root);
}
public void print_inorder(Node node) {
if (node == null) {
return;
}
print_inorder(node.left_child);
System.out.print(node.key + " ");
print_inorder(node.right_child);
}
public void print_preorder() {
print_preorder(root);
}
public void print_preorder(Node node) {
if (node == null) {
return;
}
System.out.print(node.key + " ");
print_preorder(node.left_child);
print_preorder(node.right_child);
}
public void print_postorder() {
print_postorder(root);
}
public void print_postorder(Node node) {
if (node == null) {
return;
}
print_postorder(node.left_child);
print_postorder(node.right_child);
System.out.print(node.key + " ");
}
}
This will have a node to the left if a number is even and a node to the right if a node is odd.
I had to change your if condition because the way it was it was never going to use the left node.
private void insert(Node x, int k) {
Node p = new Node(k);
if (root == null) {
this.root = p;
return;
}
if (x.getKey() - k % 2 == 0) {
if (x.left_child == null) {
x.left_child = p;
} else {
insert(x.left_child, k);
}
} else {
if (x.right_child == null) {
x.right_child = p;
} else {
insert(x.right_child, k);
}
}
}

Add Specific Object to a Binary Search Tree

I'm looking to add an object called "player" to a binary search tree based on how high the score of the player is, essentially like a scoreboard, but I'm not entirely certain how to add players to the binary tree; I'm curious how to go about writing the method, so I hope this question makes sense.
Here's a part of my BinaryTree class:
import java.util.Iterator;
public class BinaryTree implements Iterable<Player> {
private BinNode root;
public BinaryTree() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
// TODO: add the given player to the binary tree based on the player's game score
public void add(final Player player) {
if (isEmpty())
root = new BinNode(player);
// this is SUUUPER placeholder
} ...
Here's the player class, :
public class Player implements Comparable<Player> {
private String name;
private int score;
private static final int MIN_SCORE = 0;
public Player(final String name, int score) {
this.name = name;
if (score < MIN_SCORE)
this.score = 0;
else
this.score = score;
}
public Player(final String name) {
this(name, MIN_SCORE);
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
#Override
public String toString() {
return name + ": " + score;
}
// TODO: compare player objects based on their scores
#Override
public int compareTo(Player other) {
return score - other.score;// I think this is a step in the right direction???
}
}
Here's my Binary Node class:
public class BinNode {
private Player player;
private BinNode left, right;
public BinNode() {
player = null;
left = right = null;
}
public BinNode(final Player player) {
this.player = player;
left = right = null;
}
public Player getPlayer() {
return player;
}
public BinNode getLeft() {
return left;
}
public BinNode getRight() {
return right;
}
public void setPlayer(final Player data) {
this.player = player;
}
public void setLeft(BinNode left) {
this.left = left;
}
public void setRight(BinNode right) {
this.right = right;
}
#Override
public String toString() {
return player.toString();
}
}
I recommend you not to use your own trees in production, but if you are just learn, then that's fine. To add a new entity to your tree, you have to find a place for it. In this code we search for it by comparing scores of players.
public void add(final Player player){
if (isEmpty()){
root = new BinNode(player);
}
else{
BinNode node = root;
while (true){
if (player.getScore() <= node.getPlayer().getScore()){
if (node.getLeft() == null){
node.getLeft() = new BinNode(player);
return;
}
else{
node = node.getLeft();
}
}
else{
if (node.getRight() == null){
node.getRight() = new BinNode(player);
return;
}
else {
node = node.getRight();
}
}
}
}
}

How to Undo/Redo a command with JavaFX?

I have implemented the ability to undo/redo adding a number using the command pattern as seen here:
public void start(Stage stage) {
try {
CommandManager command = new CommandManager();
command.addCommand(new CommandChanger("2"));
command.undo();
command.redo();
}
}
This correctly undo's and redo's the 2. But, how can I do this with a JavaFX button click?
For reference, here is my CommandManager Class:
public class CommandManager {
private Node currentIndex = null;
private Node parentNode = new Node();
public CommandManager(){
currentIndex = parentNode;
}
public CommandManager(CommandManager manager){
this();
currentIndex = manager.currentIndex;
}
public void clear(){
currentIndex = parentNode;
}
public void addCommand(Command command){
Node node = new Node(command);
currentIndex.right = node;
node.left = currentIndex;
currentIndex = node;
}
public boolean canUndo(){
return currentIndex != parentNode;
}
public boolean canRedo(){
return currentIndex.right != null;
}
public void undo(){
//validate
if ( !canUndo() ){
throw new IllegalStateException("Cannot undo. Index is out of range.");
}
//undo
currentIndex.command.undo();
//set index
moveLeft();
}
private void moveLeft(){
if ( currentIndex.left == null ){
throw new IllegalStateException("Internal index set to null.");
}
currentIndex = currentIndex.left;
}
private void moveRight(){
if ( currentIndex.right == null ){
throw new IllegalStateException("Internal index set to null.");
}
currentIndex = currentIndex.right;
}
public void redo(){
//validate
if ( !canRedo() ){
throw new IllegalStateException("Cannot redo. Index is out of range.");
}
//reset index
moveRight();
currentIndex.command.redo();
}
private class Node {
private Node left = null;
private Node right = null;
private final Command command;
public Node(Command c){
command = c;
}
public Node(){
command = null;
}
}
}

Implement multiset using sorted linkedList

Hello I implemented a multiset using a linkedlist and I want to implement the multiset using sorted linkedlist. This is multiset abstract class.
import java.io.PrintStream;
public abstract class Multiset<T> {
/**
* Delimiter string for print operation.
*/
protected static final String printDelim = " | ";
public abstract void add(T item);
public abstract int search(T item);
public abstract void removeOne(T item);
public abstract void removeAll(T item);
public abstract void print(PrintStream out);
}
This is my implementation of linkedlist.
import java.io.PrintStream;
public class LinkedListMultiset<T> extends Multiset<T> {
protected Node mHead;
protected int mLength;
public LinkedListMultiset() {
// Implement me!
mHead = null;
mLength = 0;
}
public void add(T item) {
Node newNode = new Node((String) item);
if (mHead == null)
mHead = newNode;
else {
Node currNode = mHead;
Node parentNode = null;
while (currNode != null) {
if (currNode.getValue().
equals(newNode.getValue())) {
currNode.addCounter();
return;
}
parentNode = currNode;
currNode = currNode.getNext();
}
parentNode.setNext(newNode);
}
mLength++;
}
public int search(T item) {
Node currNode = mHead;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
return currNode.getCounter();
}
currNode = currNode.getNext();
}
return 0;
}
public void removeOne(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
currNode.minusCounter();
if (currNode.getCounter() == 0) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext
(currNode.getNext());
mLength--;
}
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void removeAll(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext(currNode.getNext());
mLength--;
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void print(PrintStream out) {
Node currNode = mHead;
while (currNode != null) {
out.printf("%s | %d\n", currNode.getValue()
, currNode.getCounter());
currNode = currNode.getNext();
}
}
private class Node {
protected String mValue;
protected Node mNext;
int counter;
public Node(String value) {
mValue = value;
mNext = null;
counter = 1;
}
public void addCounter() {
counter++;
}
public void minusCounter() {
counter--;
}
public int getCounter() {
return counter;
}
public String getValue() {
return mValue;
}
public Node getNext() {
return mNext;
}
public void setValue(String value) {
mValue = value;
}
public void setNext(Node next) {
mNext = next;
}
}
}
I want to implement sorted linkedlist but I want to change my code as minimum as possible.

how to make an .add method which adding objects in a reference based list in alphabetically order

This is my user class and i found that i have to use the compareTo method but i need a method which adding in a Rb list.
There is an already existed add method and i have make a similar which order the users alphabetically.
import java.lang.Comparable;
public class LaptopUser implements Comparable<LaptopUser>
{
private String username;
private String password;
public LaptopUser(String username,String password)
{
this.username=username;
this.password=password;
}
public String getUsername(){
return username ;
}
public String getPass()
{
return password;
}
public String toString(){
return(username+","+password);
}
#Override
public int compareTo(LaptopUser n)
{
if(this.toString().compareTo(n.toString())>0)
{
return 1;
}
else if(this.toString().compareTo(n.toString())<0)
{
return -1;
}
return 0;
}
public boolean equals(LaptopUser p)
{
return(this.toString().equals(p.toString()));
}
}
public class ReferenceBasedList implements ListInterface
{
private ListNode head;
private ListNode tail;
int numItems;
public ReferenceBasedList()
{
head = tail = null;
numItems = 0;
}
public int size()
{
return numItems;
}
public boolean isEmpty()
{
return (numItems == 0);
}
public void removeAll()
{
head = tail = null;
numItems = 0;
}
private ListNode find(int index)
{
ListNode curr = head;
for (int skip = 1; skip < index; skip++)
curr = curr.getNext();
return curr;
}
public Object get(int index)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems)
{
ListNode curr = find(index);
return curr.getItem();
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on get");
}
}
public void add(int index, Object newDataItem)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems+1)
{
if ( index == 1 )
{
ListNode newNode = new ListNode(newDataItem, head);
head = newNode;
if (tail==null)
tail = head;
}
else if ( index==numItems+1 )
{
ListNode newNode = new ListNode(newDataItem);
tail.setNext(newNode);
tail = newNode;
}
else
{
ListNode prev = find(index-1);
ListNode newNode = new ListNode(newDataItem, prev.getNext());
prev.setNext(newNode);
}
numItems++;
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on add");
}
}
public void insert(Object newDataItem)
{
this.add(1,newDataItem);
}
public void append(Object newDataItem)
{
this.add(numItems+1,newDataItem);
}
public Object showFront()
{
return this.get(1);
}
public Object showLast()
{
return this.get(numItems);
}
public void remove(int index)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems)
{
if (index == 1)
{
head = head.getNext();
if (head == null)
tail = null;
}
else
{
ListNode prev = find(index-1);
ListNode curr = prev.getNext();
prev.setNext(curr.getNext());
if (index == numItems)
tail = prev;
}
numItems--;
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on remove");
}
}
public boolean exists(Object dataItem)
{
for (ListNode tmp=head; tmp!=null; tmp=tmp.getNext())
if (tmp.getItem().equals(dataItem))
return true;
return false;
}
public Object removeLast() throws ListException
{
if (isEmpty())
throw new ListException("The linked list is empty");
else
{
Object lastDataItem = tail.getItem();
if (head == tail)
head = tail = null;
else
{
ListNode tmp = head;
while (tmp.getNext().getNext() != null)
tmp = tmp.getNext();
tail = tmp;
tail.setNext(null);
}
numItems--;
return lastDataItem;
}
}
public Object removeFront() throws ListException
{
if (isEmpty())
throw new ListException("The linked list is empty");
else
{
Object frontDataItem = head.getItem();
head = head.getNext();
if (head == null)
tail = null;
numItems--;
return frontDataItem;
}
}
}
You can use the Collections.binarySearch method to find at what index a LaptopUser should be added to a List in order for it to be alphabetically ordered.
SortedList:
public class SortedList implements Iterable<LaptopUser> {
public List<LaptopUser> users = new ArrayList<LaptopUser>();
public void add(LaptopUser user) {
int index = Collections.binarySearch(users, user);
if (index < 0)
users.add(-index - 1, user);
else
users.add(index, user);
}
#Override
public Iterator<LaptopUser> iterator() {
return users.iterator();
}
Example Code:
public class LaptopUser implements Comparable<LaptopUser> {
public String username;
public String password;
public LaptopUser(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public int compareTo(LaptopUser o) {
return toString().compareTo(o.toString());
}
#Override
public String toString() {
return username.concat(password);
}
}
public Sorted() {
LaptopUser a =new LaptopUser("a", "password");
LaptopUser b =new LaptopUser("b", "password");
LaptopUser c =new LaptopUser("c", "password");
SortedList list = new SortedList();
list.add(c);
list.add(a);
list.add(b);
for(LaptopUser user : list)
System.out.println(user);
}
public static void main(String[] args) {
new Sorted();
}
Output:
apassword
bpassword
cpassword

Categories