How to fix remove node and go to last node after? - java

I am having trouble removing a node from the user input and properly going to the last node, so it will be ready to add a new node after. I am refactoring this code to a larger implementation. However, I am unable to remove the node and go to the last node after. This is also using user input to find the proper node to remove. This is a generic linked list of a comparable type.
import java.util.Scanner;
import java.io.*;
class MyGenericList <T extends Comparable<T>>
{
private class Node<T>
{
T value;
Node<T> next;
}
private Node<T> first = null;
int count = 0;
public void add(T element)
{
Node<T> newnode = new Node<T>();
newnode.value = element;
newnode.next = null;
if (first == null)
{
first = newnode;
}
else
{
Node<T> lastnode = gotolastnode(first);
lastnode.next = newnode;
}
count++;
}
public void remove(T element)
{
Node<T> nn = new Node<T>();
Node<T> cur = first.next;
Node<T> prev = first;
nn.value = element;
boolean deleted = false;
while(cur != null && deleted == false)
{
if(cur.equals(element)) //data cannot be resolved or is not a field
{
prev.next = cur.next;
this.count--;
deleted = true;
}
}
prev = gotolastnode(prev);
prev.next = nn;
}
public T get(int pos)
{
Node<T> Nodeptr = first;
int hopcount=0;
while (hopcount < count && hopcount<pos)
{ if(Nodeptr != null)
{
Nodeptr = Nodeptr.next;
}
hopcount++;
}
return Nodeptr.value;
}
private Node<T> gotolastnode(Node<T> nodepointer)
{
if (nodepointer== null )
{
return nodepointer;
}
else
{
if (nodepointer.next == null)
return nodepointer;
else
return gotolastnode( nodepointer.next);
}
}
}
class Employee implements Comparable<Employee>
{
String name;
int age;
#Override
public int compareTo(Employee arg0)
{
// TODO Auto-generated method stub
return 0;
// implement compareto method here.
}
Employee( String nm, int a)
{
name =nm;
age = a;
}
}
class City implements Comparable<City>
{
String name;
int population;
City( String nm, int p)
{
name =nm;
population = p;
}
#Override
public int compareTo(City arg0) {
// TODO Auto-generated method stub
return 0;
// implement compareto method here.
}
}
public class GenericLinkedList
{
public static void main(String[] args) throws IOException
{
MyGenericList<Employee> ml = new MyGenericList<>();
ml.add(new Employee("john", 32));
ml.add(new Employee("susan", 23));
ml.add(new Employee("dale", 45));
ml.add(new Employee("eric", 23));
Employee e1 = ml.get(0);
System.out.println( "Name " + e1.name + " Age "+ e1.age );
ml.remove(new Employee("john", 32));
System.out.println( "Name " + e1.name + " Age "+ e1.age );
ml.add(new Employee("jerry", 35));
Employee e2 = ml.get(2);
System.out.println( "Name " + e2.name + " Age "+ e2.age );
}
}

The implementation of your remove method was faulty. Please see the fixed remove method below. Comments have been added in order to explain the changes.
The solution was tested via an online Java IDE and is verified to work properly.
public void remove(T element)
{
if(first == null) { // edge case - empty list
return;
}
else if(first.value.equals(element)) { // edge case - removing the first element
first = first.next;
this.count--;
return;
}
//Node<T> nn = new Node<T>(); // no need to create a new node, but rather remove an existing node.
Node<T> cur = first.next;
Node<T> prev = first;
//nn.value = element; //no need to create a new node and set its value attribute
boolean deleted = false;
while(cur != null && deleted == false)
{
if(cur.value.equals(element)) //data cannot be resolved or is not a field
{
prev.next = cur.next;
this.count--;
deleted = true;
}
else { // added missing advancement of the loop iterator - cur. prev must also be advanced
cur = cur.next;
prev = prev.next;
}
}
// This implementation adds the removed element to the end of the list, meaning
// it is not a remove method, but rather a move to the end implementation.
// In order to conform to what a remove method does, the last two code lines were commented out.
//prev = gotolastnode(prev);
//prev.next = nn;
}
You must also add an overridden implementation of equals in the Employee class (and other classes) which is used by your list:
class Employee implements Comparable<Employee>
{
String name;
int age;
#Override
public int compareTo(Employee arg0)
{
// sort first by name, then by age
if(name.equals(arg0.name)) {
return age - arg0.age;
}
return name.compareTo(arg0.name);
}
Employee( String nm, int a)
{
name =nm;
age = a;
}
#Override
public boolean equals(Object emp) {
boolean result = false;
if(emp != null && emp instanceof Employee) {
Employee e = (Employee)emp;
result = name.equals(e.name) && (age == e.age);
}
return result;
}
}

Related

How to create a doubly linked list of multiple data types

I am currently writing a program that creates Students and stores them in a doubly linked list based on their natural order (Last name, First name, GPA, then student ID). I am just starting off with generics and how they work so I am a little lost. I believe most of my code is working; the only part I need help with is adding students (who have multiple data types) into my list in my main method in my doubly linked list class. Any help is greatly appreciated! Here is my student, doubly linked list, and node class along with a fragment of the input file I am reading from with the data of each student:
Student class:
public class Student{
long studentID;
String firstName;
String lastName;
float GPA;
public Student(String lastName, String firstName, float GPA, long studentID){
this.lastName = lastName;
this.firstName = firstName;
this.GPA = GPA;
this.studentID = studentID;
}
public int compareTo(Student s){
int result = this.lastName.compareTo(s.lastName);
if(result == 0){
result = this.firstName.compareTo(s.firstName);
if(result == 0){
result = Float.compare(this.GPA, s.GPA);
if(result == 0){
result = Long.compare(this.studentID, s.studentID);
}
}
}
return result;
}
public String toString(){
return this.lastName + ", " + this.firstName +
" GPA: " + this.GPA + " ID: " + this.studentID;
}
}
Node class:
public class Node<T>{
Node<T> previous;
Node<T> next;
Student data;
public Node(Student data){
this(data, null, null);
}
public Node(Student data, Node<T> previous, Node<T> next){
this.data = data;
this.previous = previous;
this.next = next;
}
}
Doubly Linked List class:
import java.io.*;
import java.util.*;
import csci1140.*;
public class DoublyLinkedList<T> implements Iterable<Node>{
private Node root;
private Node tail;
private Node previous;
private class ListIterator implements Iterator<Node>{
Node current = root;
public boolean hasNext(){
return (current != null);
}
public Node next(){
Node answer;
answer = current;
current = current.next;
return answer;
}
}
public Iterator<Node> iterator(){
ListIterator listIterator = new ListIterator();
return listIterator;
}
public void add(T data){
Node<Student> newNode = new Node<Student>(data);
if(root == null){
root = newNode;
tail = root;
return;
}
Node current = root;
for( ; current!= null; current = current.next){
if(newNode.data.compareTo(current.data)<= 0){
break;
}
}
if(previous == null){
previous.next = newNode;
newNode.next = current;
if(current == null){
tail = newNode;
}
} else {
newNode.next = root;
root = newNode;
}
}
public static final void main(String[] args){
FileInputStream fileIn = null;
try{
fileIn = new FileInputStream("student_input.txt");
System.setIn(fileIn);
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace(System.err);
}
//Do work here to create list of students
}
try{
fileIn.close();
} catch(Exception e){}
}
}
Student_input.txt:
1000
Lisa
Licata
2.28
1001
Shelley
Santoro
1.56
1002
Ok
Ota
3.33
1003
Cindi
Caggiano
1.65
Still not completely sure, maybe some variation of this.
Especially this inserts before the first Node that is bigger, and I am still not sure what the generics are for in this case and T needs to be something that extends Student(well it needs the compareTo method):
public void add(T data) {
for(Node<T> current = root; current != null; current = current.next) {
if (data.compareTo(current.data) <= 0) {
current = new Node<>(data,current.previous,current);
if(null == current.previous){
root = current;
}else {
current.previous.next = current;
}
if(null == current.next){
tail = current;
} else {
current.next.previous = current;
}
return;
}
}
tail = new Node<>(data,tail,null);
if(null == tail.previous) root=tail;
}
So your list should maybe look like this(to ensure T has the compareTo method):
public class DoublyLinkedList<T extends Student> implements Iterable<Node<T>> {
...
}
All together(To have Node as a seperate file like you do is better - but for brevity I put it into the list):
public class DoublyLinkedList<T extends Student> implements Iterable<Node<T>> {
public static class Node<S> {
Node<S> previous;
Node<S> next;
S data;
public Node(S data) {
this(data, null, null);
}
public Node(S data, Node<S> previous, Node<S> next) {
this.data = data;
this.previous = previous;
this.next = next;
}
}
private Node<T> root = null;
private Node<T> tail = null;
private class ListIterator implements Iterator<Node<T>> {
Node<T> current = root;
#Override
public boolean hasNext() {
return (current != null);
}
#Override
public Node<T> next() {
Node<T> answer;
answer = current;
current = current.next;
return answer;
}
}
#Override
public Iterator<Node<T>> iterator() {
ListIterator listIterator = new ListIterator();
return listIterator;
}
public void add(T data) {
for(Node<T> current = root; current != null; current = current.next) {
if (data.compareTo(current.data) <= 0) {
current = new Node<>(data,current.previous,current);
if(null == current.previous){
root = current;
}else {
current.previous.next = current;
}
if(null == current.next){
tail = current;
} else {
current.next.previous = current;
}
return;
}
}
tail = new Node<>(data,tail,null);
if(null == tail.previous) root=tail;
}
}

How to sort a custom Linked List in Java?

I am working on a custom Linked List based on Crunchify's implementation to display list of Employee. As of now I can add new Employee or remove existing Employee from the list. However, my project requires adding a sorting method that would not be based on Collections.sort(). My teacher wants this sorting method to be custom, so this is quite difficult for me. Is there anyway to sort this list by first name that is easy to code (I'm completely new to object oriented programming)?
Here is my custom Linked List:
import java.util.Scanner;
import java.io.IOException;
public class MyLinkedListTest2 {
public static MyLinkedList linkededList;
public static void main(String[] args) {
linkededList = new MyLinkedList();
linkededList.add(new Employee("Agness", "Bed", 2000.0, 32));
linkededList.add(new Employee("Adriano", "Phuks", 4000.0, 16));
linkededList.add(new Employee("Panda", "Mocs", 6000.0, 35));
System.out.println(linkededList);
//OPTIONS
Scanner scanner = new Scanner(System.in);
int selection;
do {
System.out.println("OPTIONS:\n[1] ADD EMPLOYEE\n[2] REMOVE EMPLOYEE\n[3] SORT \n[4] EXIT\n");
selection = scanner.nextInt();
switch (selection) {
case 1:
System.out.println("Name:");
scanner.nextLine();
String name = scanner.nextLine();
System.out.println("Surname:");
String surname = scanner.nextLine();
System.out.println("Salary:");
double salary = scanner.nextDouble();
System.out.println("Experience:");
int experience = scanner.nextInt();
linkededList.add(new Employee(name, surname, salary, experience));
System.out.println(linkededList);
break;
case 2:
System.out.println("Which row do you want to remove?");
int choice = scanner.nextInt();
if (choice == 0)
System.out.println("No such row exists");
else if (choice > linkededList.size())
System.out.println("No such row exists");
else
linkededList.remove(choice - 1);
System.out.println(linkededList);
break;
case 3:
System.out.println("SORT BY: 1.NAME\t2.SURNAME\t3.SALARY\t4.EXPERIENCE\n");
//In this section sorting algorithm should be added
break;
case 4:
break;
default:
System.out.println("Wrong choice");
}
} while (selection != 4);
}
}
class MyLinkedList<Employee> {
private static int counter;
private Node head;
public MyLinkedList() {
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
}
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
while (myCurrent.getNext() != null) {
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myTemp);
}
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
public void add(Object data, int index) {
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
for (int i = 0; i < index && myCurrent.getNext() != null; i++) {
myCurrent = myCurrent.getNext();
}
}
myTemp.setNext(myCurrent.getNext());
myCurrent.setNext(myTemp);
incrementCounter();
}
public Object get(int index){
if (index < 0)
return null;
Node myCurrent = null;
if (head != null) {
myCurrent = head.getNext();
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return null;
myCurrent = myCurrent.getNext();
}
return myCurrent.getData();
}
return myCurrent;
}
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node myCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return false;
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node myCurrent = head.getNext();
while (myCurrent != null) {
output += myCurrent.getData().toString();
myCurrent = myCurrent.getNext();
}
}
return output;
}
public void compare(int index){
Node myCurrent = head.getNext();
if(myCurrent != myCurrent.getNext())
myCurrent = head;
else
myCurrent = myCurrent.getNext();
}
private class Node {
Node next;
Object data;
public Node(Object dataValue) {
next = null;
data = dataValue;
}
#SuppressWarnings("unused")
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Also, here is my Employee class that the list is based on:
public class Employee
{
private String firstName;
private String lastName;
private double salary;
private int experience;
public Employee(String firstName, String lastName, double salary, int experience)
{
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.experience = experience;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public double getSalary()
{
return salary;
}
public int getExperience()
{
return experience;
}
#Override
public String toString()
{
String ret = "\n" +"Name: "+firstName +" | Surname: "+lastName +" | Salary: "+salary + " | Experience: "+experience +"\n";
return ret;
}
}
The code is compiling now, but maybe you have some recommendation regarding this implementation of Linked List? I would be grateful if someone comes up with a solution for sorting, since with this my project will be completed. Only Comparable can be used, while Collections.sort() method cannot be implemented due to project's requirements.
You can define your own EmployeeComparator that implements Comparator<Employee> (see comparator) and use it like following :
SortedSet<Employee> set = new TreeSet<Employee>(new EmployeeComparator());
set.addAll(employees);
Since you need to implement the sorting yourself, one of the easiest way could be so compare each list node with the next one and swap them if they are not in sorted order. You need to do this until there is any such out of order nodes left in the list.
You can see bubble sort implementation for an idea on how this works.

How do I make my list a sorted list?

I am working on an assignment for a programming course I am following and I am using a List to store data. The List class:
public List() {
init();
}
protected Node<E> first, current, last;
public int numberOfNodes;
public boolean isEmpty() {
return numberOfNodes == 0;
}
public List<E> init() {
numberOfNodes = 0;
first = current = last = null;
return this;
}
public int size() {
return numberOfNodes;
}
public List<E> insert(E d) {
E copy = (E)d.clone();
if (isEmpty()) {
first = current = last = new Node(copy);
numberOfNodes += 1;
return this;
}
else{
for (current = first; current != null; current = current.next){
if(current.next== null){
current.next = last = new Node(copy);
last.prior = current;
last.next = null;
numberOfNodes += 1;
return this;
}
else{
Node<E> newNode = new Node(copy);
current.next.prior = newNode;
newNode.next = current.next;
newNode.prior = current;
current.next = newNode;
current = newNode;
numberOfNodes +=1;
return this;
}
}
}
return this;
}
public E retrieve() {
return (E) current.data.clone();
}
public List<E> remove() {
if (isEmpty()){
return init();
}
else if (numberOfNodes == 1){
return init();
}
else if (current == first) {
first = current = current.next;
current.prior = null;
numberOfNodes -= 1;
}
else if (current == last) {
last = current = current.prior;
current.next = null;
numberOfNodes -= 1;
}
else {
current.prior.next = current.next;
current.next.prior = current.prior;
current = current.next;
numberOfNodes -= 1;
}
return this;
}
public boolean find(E d) {
current = first;
while((current!=null && !(d.compareTo(current.data)==0))){
current=current.next;
}
if (current==null){
return false;
}else{
return true;
}
}
public boolean setFirst() {
if(isEmpty()){
return false;
}
else{
current = first;
return true;
}
}
public boolean setLast() {
if(isEmpty()){
return false;
}
else{
current = last;
return false;
}
}
public boolean getNext() {
if(isEmpty()||current == last){
return false;
}
else{
current = current.next;
return true;
}
}
public boolean getPrior() {
if(isEmpty()||current == first){
return false;
}
else{
current = current.prior;
return true;
}
}
public List<E> clone() {
List<E> clone;
try{
clone = (List<E>)super.clone();
} catch(CloneNotSupportedException e){
throw new Error("This cannot be cloned!");
}
clone.init();
for(Node n = first; n != null; n = n.next){
clone.insert((E)n.clone().data);
}
clone.numberOfNodes = this.numberOfNodes;
return clone;
}
Now the assignment is to make the list a sorted list, sorting the items from large to small. I need to do this in a separate class called SortedList.
I made a start, but I have really no idea on what to do next:
public class SortedList extends List implements Comparable {
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
I am using the list in my program for two different objects:
I use the list in my Set class. A set is basically a collection of natural numbers. For example: {1,2,3,4,5} is a set.
Furthermore, I use the list in my Table class. The table consists of Variables. A variable consists of a key and a value. The key is an identifier (Alfa for example) and the value is a Set {1,2,3}. The assignment is to order the items in the list from big to small.
So the SortedList needs to be a separate class that extends the list class!
How can I do this? Many many thanks!
You do not want to compare two Lists (which is what List implements Comparable implies) but to compare the lists elements -- that means, the elements have to be Comparable not the List(-type).
What makes a List a SortedList is that upon insertion of a new element, that particular element gets inserted at the correct position in the list.
To sort a list in Java you can use two interfaces: comparable and comparator.
You can use comparator, comparable or both.
Comparable is the default sort option.
Comparator can be replaced with another one, that sorts by a different value.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Demo {
private ArrayList<MyObject> list = new ArrayList<>();
public Demo() {
init();
//Collections.sort(list); //Default sort.
//Collections.sort(list, new SortByText());
//Collections.sort(list, new SortByNumberDesc());
output();
}
public void init() {
list.add(new MyObject(100, "Hello4", 654.423));
list.add(new MyObject(344, "Hello1", 65.423));
list.add(new MyObject(3465, "Hello3", 65.23));
list.add(new MyObject(43, "Hello8", 6523));
list.add(new MyObject(87, "Hello2", 654.423));
list.add(new MyObject(12432, "Hello5", 0.423));
list.add(new MyObject(-432, "Hello7", 65.3));
list.add(new MyObject(-5, "Hello6", 8979.487));
list.add(new MyObject(10, "Hello9", 549.2));
}
public void output() {
for (Iterator<MyObject> iterator = list.iterator(); iterator.hasNext();) {
MyObject next = iterator.next();
System.out.println(next.getOutput());
}
}
public static void main(String[] args) {
new Demo();
}
}
public class MyObject implements Comparable<MyObject> {
private int index;
private String text;
private double number;
public MyObject(int index, String text, double number) {
this.index = index;
this.text = text;
this.number = number;
}
public String getText() {
return text;
}
public int getIndex() {
return index;
}
public double getNumber() {
return number;
}
#Override
public int compareTo(MyObject o) {
if (index > o.index) {
return 1;
}
if (index < o.index) {
return -1;
}
return 0;
}
public String getOutput() {
return "index: " + index + " text: " + text + " number2: " + number;
}
}
import java.util.Comparator;
public class SortByText implements Comparator<MyObject> {
#Override
public int compare(MyObject o1, MyObject o2) {
return o1.getText().compareTo(o2.getText());
}
}
import java.util.Comparator;
public class SortByNumberDesc implements Comparator<MyObject> {
#Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getNumber() > o2.getNumber()) {
return -1;
}
if (o1.getNumber() < o2.getNumber()) {
return 1;
}
return 0;
}
}

Remove in Linked structure

Hello There I am trying to test removeCity(), but it didn't remove any element that I provide.
also the method addToList() if I use it in the City class I get "Exception in thread "main" java.lang.StackOverflowError" while it work fine in the test class
Any help ?
MyList
public class MyList<T> {
private Node head;
private Node tail;
public MyList(){
head = null;
tail = null;
}
public void addToTail(T info){
Node n;
//case 1: empty List
if(isEmpty()){
n = new Node(info, null);
head = n;
tail = head;
}
//case 2: if the list is not empty
else {
n = new Node(info, null);
tail.setNext(n);
tail = n;
}
}
public void addToHead(T info){
Node n;
//case 1: empty List
if(isEmpty()){
n = new Node(info, null);
head = n;
tail = head;
}
//case 2: if the list is not empty
else {
n = new Node(info, head);
head = n;
}
}
public boolean removeHead(){
//Case 1: if the list is empty
if(isEmpty())
return false;
//case 2: if the list have at least one element
else{
Node n = head.getNext();
head = n;
return true;
}
}
public boolean removeElement(String element){
//cacs 1 if before is the head
if(isEmpty())
return false;
if( ((City) head.getInfo()).getCode().equals(element)){
removeHead();
return true;
}
Node iter = head.getNext();
Node prev = head;
while(iter != null && !((City) head.getInfo()).getCode().equals(element)){
iter = iter.getNext();
prev = prev.getNext();
}
if(iter == null)
return false;
else{
prev.setNext(iter.getNext());
return true;
}
}
//To check if the list is empty
public boolean isEmpty(){
if ( head == null)
return true;
else
return false;
}
Node
public class Node<T> {
private T info;
private Node next;
public Node(){
info = null;
next = null;
}
public Node(T info, Node next){
this.info = info;
this.next = next;
}
public T getInfo(){
return info;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
public void setInfo(T info){
this.info = info;
}
}
City
public class City implements Serializable {
public static MyList<City> cityList = new MyList<City>();
private String name;
private String code;
public City(String name, String code) {
super();
this.name = name;
this.code = code;
addToList(new City(name,code));
}
public void addToList(City toAdd){
City.cityList.addToHead(toAdd);
}
public static void removeCity(String name){
if( cityList.isEmpty()){
System.out.println("The List is empty");
return;
}
if ( cityList.removeElement(name) == true )
System.out.println("The City was removed sucssesfully");
else
System.out.println("This city does not not exist");
}
}
Test
public class DummyTest {
public static void main(String [] args){
City x = new City("Ney York","NY");
City y = new City("London","LD");
System.out.println(City.cityList);
}
}
Stacktrace
Exception in thread "main" java.lang.StackOverflowError
at City.<init>(City.java:15)
at City.<init>(City.java:18)
at City.<init>(City.java:18)
Line 15 is the constructor
public City(String name, String code)
Line 18 is addToList
addToList(new City(name,code))
What I've spotted that you have an issue in your while loop in removeElement method.
I am not sure if it will solve your issue.
Could you also put a part of stacktrace here were do you get StackOverflowException.
Node iter = head.getNext();
Node prev = head;
while(iter != null && !((City) head.getInfo()).getCode().equals(element)){
iter = iter.getNext();
prev = prev.getNext();
}
this line
while(iter != null && !((City) head.getInfo()).getCode().equals(element))
should be probably
while(iter != null && !((City) iter.getInfo()).getCode().equals(element))
iter instead head
Alexey already found the first error, here are 2 more:
public City(String name, String code) {
super();
this.name = name;
this.code = code;
addToList(new City(name,code)); // <- infinite recursion
}
is infinite recursion: the (constructor-)method calls the (constructor-)method.
It should probably be addToList(this);
Also: In mylist.java all the new Node(..) should be new Node<T>(..).

AddressBook using a binary search tree in java [duplicate]

This question already exists:
Write an address book in java using a binary search tree [closed]
Closed 9 years ago.
Hello I am writing an AddressBook application in java and I have written the whole program. The only thing is that its not working as expected and there are no errors in the code so i am unable to troubleshoot it. Any help would be much appriciated.
EDIT: This is not a duplicate question as this includes all the methods. The other one didn't have the main method and is incomplete and as it was closed i was forced to ask a new question. Makes sense?
package com.addressbook;
public abstract class KeyedItem<KT extends Comparable<? super KT>> {
private KT searchKey;
public KeyedItem(KT key){
searchKey = key;
}
public KT getKey(){
return searchKey;
}
}
package com.addressbook;
public class People extends KeyedItem<String> {
private String address;
private String phone;
public People(String n, String a, String p){
super(n);
this.address = a;
this.phone = p;
}
public void setAddress(String a){
address = a;
}
public void setPhone(String p){
phone = p;
}
public String toString(){
return "Name:" + getKey() + "\nAddress:" + address + "\nPhone:" + phone;
}
public String getTheKey(){
return getKey();
}
}
package com.addressbook;
public class BinaryNode{
// Friendly data; accessible by other package routines
private People people; // The data in the node
private BinaryNode left; // Left child
private BinaryNode right; // Right child
// Constructors
public BinaryNode(People pe, BinaryNode l, BinaryNode r) {
people = pe;
left = l;
right = r;
}
public BinaryNode(People pe) {
people = pe;
left = right = null;
}
public void setData(People p){
people = p;
}
public String getSearch(){
return people.getTheKey();
}
public People getData(){
return people;
}
public BinaryNode getLeft(){
return left;
}
public BinaryNode getRight(){
return right;
}
}
package com.addressbook;
import com.addressbook.People;
import com.addressbook.BinaryNode;
public class AddressBook {
private BinaryNode root;
public AddressBook() {
super();
}
public AddressBook(People p) {
super();
root = new BinaryNode(p);
}
public void insert(People p){
insert(p, root);
}
public People get(String key) {
BinaryNode node = root;
while (node != null) {
if (key.compareTo(node.getSearch()) == 0) {
return node.getData();
}
if (key.compareTo(node.getSearch()) < 0) {
node = node.getLeft();
} else {
node = node.getRight();
}
}
return null;
}
protected BinaryNode insert(People p, BinaryNode node) {
if (node == null) {
return new BinaryNode(p);
}
if (p.getTheKey().compareTo(node.getSearch()) == 0) {
return new BinaryNode(p, node.getLeft(), node.getRight());
} else {
if (p.getTheKey().compareTo(node.getSearch()) < 0) { // add to left subtree
insert(p, node.getLeft());
} else { // add to right subtree
insert(p, node.getRight());
}
}
return node;
}
public void remove(String key) {
remove(key, root);
}
protected BinaryNode remove(String k, BinaryNode node) {
if (node == null) { // key not in tree
return null;
}
if (k.compareTo(node.getSearch()) == 0) { // remove this node
if (node.getLeft() == null) { // replace this node with right child
return node.getRight();
} else if (node.getRight() == null) { // replace with left child
return node.getLeft();
} else {
// replace the value in this node with the value in the
// rightmost node of the left subtree
node = getRightmost(node.getLeft());
// now remove the rightmost node in the left subtree,
// by calling "remove" recursively
remove(node.getSearch(), node.getLeft());
// return node; -- done below
}
} else { // remove from left or right subtree
if (k.compareTo(node.getSearch()) < 0) {
// remove from left subtree
remove(k, node.getLeft());
} else { // remove from right subtree
remove(k, node.getRight());
}
}
return node;
}
protected BinaryNode getRightmost(BinaryNode node) {
assert(node != null);
BinaryNode right = node.getRight();
if (right == null) {
return node;
} else {
return getRightmost(right);
}
}
protected String toString(BinaryNode node) {
if (node == null) {
return "";
}
return node.getData().toString() + "(" + toString(node.getLeft()) + ", " +
toString(node.getRight()) + ")";
}
public static void main(String[] arguments) {
AddressBook tree = new AddressBook();
People p1 = new People("person 1", "adresa 1", "404040404");
People p2 = new People("person 2", "adresa 2", "4040434345");
People p3 = new People("person 3", "adresa 3", "346363463");
People p4 = new People("person 4", "adresa 4", "435346346");
People p5 = new People("person 5", "adresa 5", "4363907402");
tree.insert(p1);
tree.insert(p2);
tree.insert(p3);
tree.insert(p4);
tree.insert(p5);
System.out.println(tree.get("person 1"));
}
}
On one hand:
public void insert(People p){
insert(p, root);
}
but that method begins with
protected BinaryNode insert(People p, BinaryNode node) {
if (node == null) {
return new BinaryNode(p);
}
which means, considering both pieces together, you always ignore the new root and hence your tree never fills. Try this instead:
public void insert(People p){
root = insert(p, root);
}
In the same manner you ignore the return value of insert inside insert too. You should handle them in a similar manner.

Categories