Adding first node before last node - java

I have some problems with java(Dobly Linked List). i must add first node before last node. at first tried to build it, but not works. hier is my dobly linked list:
public class DoublyLinkedList<T>
{
private Element<T> first, last;
private int size;
public DoublyLinkedList()
{
first = last = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
// --- hier is Problem!!! I have changed just hier. ---
public void apply( T o ) {
Element<T> e = new Element<T>(o);
Element<T> current = first;
Element<T> save = first;
for(int i = 0; i < size; i++){
current = current.getNext();
}
current.connectAsPrevious(e);
e.connectAsNext(save);
size++;
}
// --- bekannte Methoden ---
public void add( T content )
{
Element<T> e = new Element<T>( content );
if ( isEmpty() )
{
first = last = e;
}
else
{
last.connectAsNext( e );
last = e;
}
size++;
}
public void showAll()
{
Element<T> current = first;
while ( current != null )
{
if ( current.getContent() != null )
{
System.out.print( current.getContent().toString() );
if ( current != last )
{
System.out.print(", ");
}
}
current = current.getNext();
}
System.out.println();
}
// --- weitere Methoden zum Testen ---
public void build( T[] elems )
{
for ( T e : elems ) { add( e ); }
}
public String toString()
{
String result = "";
Element current = first;
while ( current != null )
{
result += current.getContent().toString();
if ( current != last )
{
result += ", ";
}
current = current.getNext();
}
return result;
}
// Element
private static class Element<E>
{
private E content;
private Element<E> previous, next;
public Element( E c )
{
content = c;
previous = next = null;
}
public E getContent()
{
return content;
}
public void setContent( E c )
{
content = c;
}
public boolean hasNext()
{
return next != null;
}
public Element<E> getNext()
{
return next;
}
public void disconnectNext()
{
if ( hasNext() )
{
next.previous = null;
next = null;
}
}
public void connectAsNext( Element<E> e)
{
disconnectNext();
next = e;
if ( e != null )
{
e.disconnectPrevious();
e.previous = this;
}
}
public boolean hasPrevious()
{
return previous != null;
}
public Element<E> getPrevious()
{
return previous;
}
public void disconnectPrevious()
{
if ( hasPrevious() )
{
previous.next = null;
previous = null;
}
}
public void connectAsPrevious( Element<E> e )
{
disconnectPrevious();
previous = e;
if ( e != null )
{
e.disconnectNext();
e.next = this;
}
}
}
}
I think i must add whileloop. because if size 0 is, it stops on it and comes error NullPointerException. sorry for my bad english.

The reason you get a NullPointerException is that if you have an empty list then current is null (because it's assigned the value of first which is null) and current.connectAsPrevious will throw the exception.
Without knowing what the method is supposed to do it's difficult to suggest an alternative. However you can avoid the exception by putting if (current != null) before current.connectAsPrevious.
If it is supposed to add the item before the last item in the list (rather than as the last item) then you should just use your last reference rather than iterating through the list from the start:
e.connectAsNext(last);
e.connectAsPrevious(last.getPrevious());
last.connectAsPrevious(e);

Related

Iterator for a Binary Search Tree do not go down the tree

I've been struggling with implementing a Binary Search Tree with the Iterator method. I've been checking out this algorithm out on WikiPedia:
def search_recursively(key, node):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursively(key, node.left)
# key > node.key
return search_recursively(key, node.right)
I translated it to Java:
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private int count = 0;
#Override
public boolean hasNext()
{
return count++ < size;
}
#Override
public T next()
{
return search(root, root.word);
}
public T search(BST root, T word)
{
if (root == null || root.word.compareTo(word) == 0)
{
return root.word;
}
if (root.word.compareTo(word) < 0)
{
return search(root.left, word);
}
return search(root.right, word);
}
};
When trying to run the program I only get the root element of the BST:
MyWordSet bst = new MyWordSet();
T bst = new T("one");
T bst = new T("two");
T bst = new T("three");
T bst = new T("four");
T bst = new T("five");
T bst = new T("six");
bst.add(w1);
bst.add(w2);
bst.add(w3);
bst.add(w4);
bst.add(w5);
bst.add(w6);
Iterator<T> it = bst.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
So the output is:
one
one
one
one
one
one
So why does this method inside my Iterator not work for me to get to the whole tree? I really can't figure out what is wrong here and why it only prints out one when it should go down the tree.
You simply do not update the current_node.
The equivalent of current_node = node is missing.
Well, after having changed the code, here revised answer:
import java.util.Iterator;
import java.util.Stack;
/**
*
* #author jk
*/
public class BSTIterator<T> implements Iterator<T> {
public static final class BST<T> {
private BST<T> left;
private BST<T> right;
private T word;
private BST(T word) {
this.word = word;
}
}
private final Stack<BST<T>> stackBST = new Stack<>();
public BSTIterator(final BST<T> root) {
// push all most left entries of the tree to the stack
BST<T> currBST = root;
while (currBST != null) {
stackBST.push(currBST);
currBST = currBST.left;
}
}
#Override
public boolean hasNext() {
return !stackBST.isEmpty();
}
#Override
public T next() {
BST<T> currBST = stackBST.pop();
// check if we are on the most right entry
final boolean notMostRightEntry = currBST.right != null;
if (notMostRightEntry) {
// take next right entry
BST<T> nextBST = currBST.right;
while (nextBST != null) {
// push this next right entry on the stack
stackBST.push(nextBST);
nextBST = nextBST.left;
}
}
return currBST.word;
}
public static void main(String[] args) {
BST<Integer> root = new BST<>(20);
root.left = new BST<>(5);
root.right = new BST<>(30);
root.left.right = new BST<>(10);
root.right.left = new BST<>(25);
root.right.right = new BST<>(40);
root.right.left = new BST<>(35);
root.right.left.left = new BST<>(32);
for (Iterator<Integer> bstIt = new BSTIterator<>(root); bstIt.hasNext();) {
System.out.println("val: " + bstIt.next());
}
}
}

Counting how many of that "element" appear in a doubly linked list

I have a problem with my nbSandwichs(int type) method
It is supposed to go through the doubly linked list and count how many times a sandwitch of the same type appear, everything is good except for the last sandwich that prints 0 which is something that I don't understand, my check method is saying that it doesn't exist but when I created a get last method, it actually does exist. What condition is missing in my nbSandwichs method ? Does my while loop actually doesn't get to the last node??
Thank you
main class :
Sandwich s1 = new Sandwich(1);
Sandwich s1 = new Sandwich(1);
Sandwich s2 = new Sandwich(15);
Sandwich s3 = new Sandwich(15);
Sandwich s4 = new Sandwich(4);
Sandwich s5 = new Sandwich(15);
APreparer a1 = new APreparer();
a1.addfirst(s1);
a1.addfirst(s2);
a1.addfirst(s3);
a1.addfirst(s4);
a1.addfirst(s5);
System.out.println(a1.nbSandwichs(15)); // PRINTS : 3 OK
System.out.println(a1.nbSandwichs(1)); // PRINTS : 0 NOT OK
public class Sandwich {
private int type;
public Sandwich(int type) {
this.type = type;
commandes[type]++;
}
public class APreparer {
private UneCommande first;
private UneCommande last;
public void addfirst(Sandwich sandwich) {
UneCommande nouvelle = new UneCommande(sandwich);
if (first == null) {
first = nouvelle;
last = nouvelle;
} else {
first = first.addFirst(sandwich);
}
}
int nbSandwichs(int type) {
if (first == null) {
return 0;
} else {
return first.nbSandwichs(type);
}
}
}
public class UneCommande {
private Sandwich sandwich;
private UneCommande next;
private UneCommande previous;
public UneCommande(Sandwich sandwich) {
this.sandwich = sandwich;
}
public UneCommande addFirst(Sandwich sandwich) {
UneCommande current = this;
UneCommande newSand = new UneCommande(sandwich);
newSand.next = current;
this.previous = newSand;
return newSand;
}
int nbSandwichs(int type) {
int counter = 0;
UneCommande current = this;
if (!(check(type))) {
return 0;
} else {
while (current.next != null) {
if (current.sandwich.getType() == type) {
counter++;
}
current = current.next;
}
}
return counter;
}
boolean check(int type) {
UneCommande current = this;
while (current != null) {
if (current.sandwich.getType() == type) {
System.out.println("EXIST");
return true;
}
current = current.next;
}
return false;
}
}
Your loop counts nodes as long as current.next != null. When current is the last node in your list, current.next will be null, and thus not counted.

Binary Search Tree Print Range

So I have to modify the BST class to include a PrintRange function, which would essentially print all nodes between two values in order.
Here is the class
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
import java.lang.Comparable;
/** Binary Search Tree implementation for Dictionary ADT */
class BST<Key extends Comparable<? super Key>, E>
implements Dictionary<Key, E> {
private BSTNode<Key,E> root; // Root of the BST
int nodecount; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
#param k Key value of the record.
#param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
#param k Key value of record to remove.
#return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
#return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** #return Record with key value k, null if none exist.
#param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** #return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode<Key,E> rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** #return The current subtree, modified to contain
the new item */
private BSTNode<Key,E> inserthelp(BSTNode<Key,E> rt,
Key k, E e) {
if (rt == null) return new BSTNode<Key,E>(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
#return The tree with the node removed */
private BSTNode<Key,E> removehelp(BSTNode<Key,E> rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode<Key,E> temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right()));
}
}
return rt;
}
private BSTNode<Key,E> getmin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt;
return getmin(rt.left());
}
private BSTNode<Key,E> deletemin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt.right();
rt.setLeft(deletemin(rt.left()));
return rt;
}
private void printhelp(BSTNode<Key,E> rt) {
if (rt == null) return;
printhelp(rt.left());
printVisit(rt.element());
printhelp(rt.right());
}
private StringBuffer out;
public String toString() {
out = new StringBuffer(400);
printhelp(root);
return out.toString();
}
private void printVisit(E it) {
out.append(it + "\n");
}
public void printPreOrder(BSTNode<E, E> root) {
if (root != null) {
System.out.println(root.element());
printPreOrder(root.left());
printPreOrder(root.right());
}
}
public void printInOrder(BSTNode<E, E> root) {
if (root != null) {
printInOrder(root.left());
System.out.println(root.element());
printInOrder(root.right());
}
}
public void printPostOrder(BSTNode<E, E> root) {
if (root != null) {
printPostOrder(root.left());
printPostOrder(root.right());
System.out.println(root.element());
}
}
}
Here's what I have so far for the PrintRange function:
public void printRange(BSTNode<E, E> root, E low, E high) {
if (root != null) {
printRange(root.left(), low, high);
if (root.element().toString().compareTo(low.toString()) > 0 && root.element().toString().compareTo(high.toString()) < 0)
System.out.println(root.element());
printRange(root.right(), low, high);
}
}
But it's giving me an error. Any suggestions on how to compare elements/nodes/I'm not even certain in a BST?
Here's the driver if it helps
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Lab8a {
public static void main(String[] args) {
BST<String, String> tree = new BST<String, String>();
Scanner fileScan = null, scan = new Scanner(System.in);
//Open file
try {
fileScan = new Scanner(new File("inventory.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Reads elements from file
while (fileScan.hasNextLine()) {
String s = fileScan.nextLine();
tree.insert(s, s);
}
System.out.println("\nRange");
tree.printRange(tree.getRoot(), "A", "B");
}
}
And the text file:
CT16C1288B
DT14B1225F
MI15B1250A
MI15B1251A
HO03N1095A
HY07D1095BQ
KI04D2593C
DG12A1240AQ
HY03G2593BQ
TO30A1310A
HO03N1095AQ
HO01H1351C
HO01H1350C
FT18A1288B
LR15A1000A
BM12E1000A
VW02B3113A
NI23H1230AQ
LX03D2503A
LX03D2502A
LX03D2502A
VW22A3113B
VW22B3113A
I was mistaken. There was no error. I must have fixed the code at some point.

How to get the first element when going through a binary search tree with inorder?

My try (gave me a NullPointerException):
public Karte giveFirst(BinarySearchTree<Karte> t){
if(t.getLeftTree() != null) {
return giveFirst(t.getLeftTree());
}else{
return t.getContent();
}
}
Complete Binary Search Tree Code:
package Model;
private class BSTNode<CT extends ComparableContent<CT>> {
private CT content;
private BinarySearchTree<CT> left, right;
public BSTNode(CT pContent) {
this.content = pContent;
left = new BinarySearchTree<CT>();
right = new BinarySearchTree<CT>();
}
}
private BSTNode<ContentType> node;
public BinarySearchTree() {
this.node = null;
}
public void insert(ContentType pContent) {
if (pContent != null) {
if (isEmpty()) {
this.node = new BSTNode<ContentType>(pContent);
} else if (pContent.isLess(this.node.content)) {
this.node.left.insert(pContent);
} else if(pContent.isGreater(this.node.content)) {
this.node.right.insert(pContent);
}
}
}
public BinarySearchTree<ContentType> getLeftTree() {
if (this.isEmpty()) {
return null;
} else {
return this.node.left;
}
}
public ContentType getContent() {
if (this.isEmpty()) {
return null;
} else {
return this.node.content;
}
}
public BinarySearchTree<ContentType> getRightTree() {
if (this.isEmpty()) {
return null;
} else {
return this.node.right;
}
}
public void remove(ContentType pContent) {
if (isEmpty()) {
return;
}
if (pContent.isLess(node.content)) {
node.left.remove(pContent);
} else if (pContent.isGreater(node.content)) {
node.right.remove(pContent);
} else {
if (node.left.isEmpty()) {
if (node.right.isEmpty()) {
node = null;
} else {
node = getNodeOfRightSuccessor();
}
} else if (node.right.isEmpty()) {
node = getNodeOfLeftSuccessor();
} else {
if (getNodeOfRightSuccessor().left.isEmpty()) {
node.content = getNodeOfRightSuccessor().content;
node.right = getNodeOfRightSuccessor().right;
} else {
BinarySearchTree<ContentType> previous = node.right
.ancestorOfSmallRight();
BinarySearchTree<ContentType> smallest = previous.node.left;
this.node.content = smallest.node.content;
previous.remove(smallest.node.content);
}
}
}
}
public ContentType search(ContentType pContent) {
if (this.isEmpty() || pContent == null) {
return null;
} else {
ContentType content = this.getContent();
if (pContent.isLess(content)) {
return this.getLeftTree().search(pContent);
} else if (pContent.isGreater(content)) {
return this.getRightTree().search(pContent);
} else if (pContent.isEqual(content)) {
return content;
} else {
return null;
}
}
}
private BinarySearchTree<ContentType> ancestorOfSmallRight() {
if (getNodeOfLeftSuccessor().left.isEmpty()) {
return this;
} else {
return node.left.ancestorOfSmallRight();
}
}
private BSTNode<ContentType> getNodeOfLeftSuccessor() {
return node.left.node;
}
private BSTNode<ContentType> getNodeOfRightSuccessor() {
return node.right.node;
}
}
How can I change/rewrite my code for it to work?
Think what would happen when you reach the left most leaf node.
Its left tree will be null which means you will break out of the while loop. You are returning null after this and so any attempt to access the state of the return value will throw an exception.
You must return this node when it has no more left children as that will be the smallest element in the tree
Also, I don't know why you have BinarySearchTree and BSTNode. A BSTNode should be good enough to construct a tree. Please go through some tutorial/lessons for a better understanding.
How to get the first element when going through a binary search tree with inorder?
Keep going left till you can't go left anymore... If a node has a left child, go for it. Keep doing this till you get to a node that does not have a left child. When you are there, you know you are in the left-most part of the tree. Following code snippet shows an idea of how this can be achieved given the root of a BST.
public BSTNode getSmallest(BSTNode root) {
if(root.left != null)
return getSmallest(root.left);
return root;
}

How to check if member exists

So i have implemented the insert method and it works just fine but my problem is how to check whether a member is already in the list or not,i want the program to check if the member is already in the list but the checker doesn't work. i want the program to put the member in team1 if the member is included in the list and Display "member does not exist" if the member is not on the list. I made a check method but it doesn't work. I am new in Programming and i really need help. Please enlighten me with your knowledge.
class Node
{
protected String info;
protected Node next;
public Node(String value)
{
info = value;
next = null;
}
}
class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
head = null;
count = 0;
}
public void insert( String name)
{
Node a = new Node(name);
a.next = null;
count++;
if (head == null)
{
head = a;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = a;
return;
}
}
}
public void checker(String name)
{
for(Node cur = head; cur != null; cur = cur.next)
{
if(cur.info == name)
{
insertteam1(name);
System.out.print("OK");
}
else
{
System.out.print("member does not exist");
}
}
}
public void insertteam1(String name)
{
Node b = new Node(name);
b.next = null;
count++;
if (head == null)
{
head = b;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = b;
return;
}
}
}
In the code below,
if(cur.info == name){ // }
you are comparing the string info using == which is not the right way to compare strings in java.
Use
if(cur.info.equals(name)){ // }
or
use if(cur.info.equalsIgnoreCase(name)){ // } if you want to do case insensitive compare.

Categories