Printing linked list from binary search tree - java

I'm writing a program that has a binary search tree (Roster) that Student objects are inserted to by their String Id. Each student has a linked list that their courses are added to containing the String of the course and their grade. The binary search tree is my own version of an implementation.
I'm having trouble implementing my method to print the students that all contain a specific course. I think my implementation is off in my printCourse method as I can't call to it from my displayStudent() method under my Roster class. This is a homework assignment and I have most of the other methods implemented, just struggling with this one, any help is greatly appreciated!
displayStudents("Math161");
is the method i'm correctly struggling to implement. It calls from the method in my roster class, which i'm trying to implement to search through my BST
In my BST the method printCourse() should check each students linked list and if it contains the course listed above and print each student that does. Here's what I have so far, which is not correct:
> public void printCourse(Node n, String course) {
> if (n != null) {
> inOrder(n);
> if (n.element.getId().equals(course)) {
> System.out.print(n.element.getId() + " ");
> }
> }
> }
Homework5.class / Main:
public class Homework5 {
static Roster rost = new Roster();
public static void main(String[] args) {
addStudent();
displayAllStudents();
lookupStudent("11114");
addCourse();
displayStudents("Math161");
}
// add students to the roster
static void addStudent() {
rost.addStudent(new Student("11111", "Jon", "Benson"));
rost.addStudent(new Student("11112", "Erick", "Hooper"));
rost.addStudent(new Student("11113", "Sam", "Shultz"));
rost.addStudent(new Student("11114", "Trent", "Black"));
rost.addStudent(new Student("11115", "Michell", "Waters"));
rost.addStudent(new Student("11116", "Kevin", "Johnson"));
}
// display all students in the roster
static void displayAllStudents() {
rost.displayAllStudents();
}
// lookup a student in the roster
static void lookupStudent(String id) {
if (rost.find(id) != null) {
System.out.println(id + " found");
} else {
System.out.println(id + " not found");
}
}
// add courses to the roster
static void addCourse() {
rost.addCourse("11111", new Course("CS116", 80));
rost.addCourse("11111", new Course("Math161", 90));
rost.addCourse("11112", new Course("Math161", 70));
rost.addCourse("11112", new Course("CS146", 90));
rost.addCourse("11112", new Course("CS105", 85));
rost.addCourse("11113", new Course("CS216", 90));
rost.addCourse("11114", new Course("CIS255", 75));
rost.addCourse("11114", new Course("CS216", 80));
rost.addCourse("11114", new Course("Math161", 60));
rost.addCourse("11114", new Course("COMM105", 90));
}
// display students enrolled in a given course id
static void displayStudents(String courseId) {
rost.displayStudents(courseId);
}
}
Student.class:
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
LinkedList<Course> courses = new LinkedList<>();
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(Course course) {
courses.add(course);
}
}
Course.class:
class Course {
LinkedList<Course> course = new LinkedList<>();
String id; // course id
int grade;
Course(String id, int grade) {
this.id = id;
this.grade = grade;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getGrade() {
return grade;
}
public void setId(int grade) {
this.grade = grade;
}
}
Roster.class:
class Roster {
Student root;
int numStudents;
BST<Student> roster = new BST<>();
LinkedList<Course> courseList = new LinkedList<>();
public Roster() {
root = null;
numStudents = 0;
}
public void addStudent(Student st) {
roster.insert(st);
numStudents++;
}
public void displayAllStudents() {
roster.traverse(2);
}
public Student find(String id) {
return roster.find(id);
}
public void addCourse(String id, Course course) {
Student student = roster.find(id);
student.addCourse(course);
}
public void displayStudents(String courseId) {
roster.printCourse(courseId);
}
}
BST.java
class BST<Roster extends Comparable> {
private Node root;
public BST() {
root = null;
}
// Generic find method
public Student find(String id) {
Node current = root;
while (id.compareTo(current.element.getId()) != 0) {
if (id.compareTo(current.element.getId()) < 0) {
current = current.left;
}
else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current.element;
}
public void insert(Student st) {
Node newNode = new Node(st);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (st.getId().compareTo(current.element.getId()) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
public void printCourse(Node n, String course) {
if (n != null) {
inOrder(n);
if (n.element.getId().equals(course)) {
System.out.print(n.element.getId() + " ");
}
}
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print("\nPreorder traversal: ");
// call preOrder(root) and implement preOrder()
preOrder(root);
break;
case 2:
System.out.print("\nList of all students: ");
inOrder(root);
break;
case 3:
System.out.print("\nPostorder traversal: ");
// call postOrder(root) and implement postOrder()
postOrder(root);
break;
}
System.out.println();
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element.getId() + " ");
inOrder(localRoot.right);
}
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
System.out.print(localRoot.element + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.element + " ");
}
}
}
class Node {
protected Student element;
protected Node left;
protected Node right;
public Node(Student st) {
element = st;
}
}

I don't know if this is everything, but two things that I see that seem wrong are:
In the Roster.class: The roster.printCourse(courseId) call in displayStudents() only includes one parameter, the courseId, but the printCourse() method in BST.java has two parameters, a Node and a String.
In the Roster.class: The BST called roster is given a type <Student>, but the definition of BST in BST.java has it containing a Roster, not a Student. Note: You don't need to use <> with a type inside unless that type can change. If BST can only be applied to the type Student, then you don't need that in the definition or the creation of BST. On the other hand, if your BST should work for any type of data, you should define the BST as class BST <T extends Comparable> and make sure to use T wherever the type should go. (Look up Generic Types on Google for more examples.)

Related

Checking if value in linked list is equal to String at each node

I'm writing a program for a homework assignment that has a binary search tree (Roster) that Student objects are inserted to by their String Id. Each student has a linked list that their courses are added to containing the String of the course and their grade. The binary search tree is my own version of an implementation.
I'm having trouble implementing my method to print the students that all contain a specific course. I think my implementation is off in my printCourseHelper() method as the if condition isn't working properly to check if the value in the list at each node is equal to the given value.
I'm looking for all student's enrolled in the course "Math161" which should be 3, and the String ID's of the student's in that class would be printed. I'm not getting any errors when I run my program, however only the functions being called above my displayStudents() are printing.
My issues I believe are in my BST.java, printCourse and printCourseHelper methods:
public void printCourse(String course) {
printCourseHelper(root, course);
}
public void printCourseHelper(Node n, String course) {
if(n.element.getCourseList().contains(course)) {
System.out.print(n.element.getId() + " ");
}
if (n.left != null) {
printCourseHelper(n.left, course);
}
if (n.right != null) {
printCourseHelper(n.right, course);
}
}
Homework5.class / main:
import java.util.LinkedList;
public class Homework5 {
static Roster rost = new Roster();
public static void main(String[] args) {
addStudent();
displayAllStudents();
lookupStudent("11114");
addCourse();
displayStudents("Math161");
}
// add students to the roster
static void addStudent() {
rost.addStudent(new Student("11111", "Jon", "Benson"));
rost.addStudent(new Student("11112", "Erick", "Hooper"));
rost.addStudent(new Student("11113", "Sam", "Shultz"));
rost.addStudent(new Student("11114", "Trent", "Black"));
rost.addStudent(new Student("11115", "Michell", "Waters"));
rost.addStudent(new Student("11116", "Kevin", "Johnson"));
}
// display all students in the roster
static void displayAllStudents() {
rost.displayAllStudents();
}
// lookup a student in the roster
static void lookupStudent(String id) {
if (rost.find(id) != null) {
System.out.println(id + " found");
} else {
System.out.println(id + " not found");
}
}
// add courses to the roster
static void addCourse() {
rost.addCourse("11111", new Course("CS116", 80));
rost.addCourse("11111", new Course("Math161", 90));
rost.addCourse("11112", new Course("Math161", 70));
rost.addCourse("11112", new Course("CS146", 90));
rost.addCourse("11112", new Course("CS105", 85));
rost.addCourse("11113", new Course("CS216", 90));
rost.addCourse("11114", new Course("CIS255", 75));
rost.addCourse("11114", new Course("CS216", 80));
rost.addCourse("11114", new Course("Math161", 60));
rost.addCourse("11114", new Course("COMM105", 90));
}
// display students enrolled in a given course id
static void displayStudents(String courseId) {
rost.displayStudents(courseId);
}
// display courses taken by a student
static void displayCourses(String id) {
rost.displayCourses("id");
}
// display the average grade for a student
static void getCourseAverage(String courseId) {
rost.getCourseAverage(courseId);
}
// display the average grade for a student
static void dropCoursesBelow(String id, int grade) {
rost.dropCoursesBelow(id, grade);
}
// drop a course from a student
static void dropCourse(String id, String courseId) {
rost.dropCourse(id, courseId);
}
// change the grade for a student
static void changeGrade(String id, String courseId, int grade) {
rost.changeGrade(id, courseId, grade);
}
}
Student.class
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
LinkedList<Course> courses = new LinkedList<>();
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(Course course) {
courses.add(course);
}
public LinkedList<Course> getCourseList() {
return courses;
}
}
Course.class:
class Course {
LinkedList<Course> course = new LinkedList<>();
String id; // course id
int grade;
Course(String id, int grade) {
this.id = id;
this.grade = grade;
}
public String getCourseId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getGrade() {
return grade;
}
public void setId(int grade) {
this.grade = grade;
}
}
Roster.class:
class Roster {
Student root;
int numStudents;
BST<Student> roster = new BST<>();
LinkedList<Course> courseList = new LinkedList<>();
public Roster() {
root = null;
numStudents = 0;
}
public void addStudent(Student st) {
roster.insert(st);
numStudents++;
}
public void displayAllStudents() {
roster.traverse(2);
}
public Student find(String id) {
return roster.find(id);
}
public void addCourse(String id, Course course) {
Student student = roster.find(id);
student.addCourse(course);
}
public void displayStudents(String courseId) {
roster.printCourse(courseId);
}
}
BST.java
class BST<Roster extends Comparable> {
private Node root;
public BST() {
root = null;
}
// Generic find method
public Student find(String id) {
Node current = root;
// Loop until e.compare to current element is not equal to 0
while (id.compareTo(current.element.getId()) != 0) {
//!!! implement
// if e.compare is less than 0 set current to current.left
if (id.compareTo(current.element.getId()) < 0) {
current = current.left;
} // else if current is 0 or greater than 0 set current
// to current.right
else {
current = current.right;
}
// if current is null, return null
if (current == null) {
return null;
}
}
// return current value when loop ends
return current.element;
}
public void insert(Student st) {
Node newNode = new Node(st);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (st.getId().compareTo(current.element.getId()) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
public void printCourse(String course) {
printCourseHelper(root, course);
}
public void printCourseHelper(Node n, String course) {
if(n.element.getCourseList().contains(course)) {
System.out.print(n.element.getId() + " ");
}
if (n.left != null) {
printCourseHelper(n.left, course);
}
if (n.right != null) {
printCourseHelper(n.right, course);
}
}
public void traverse(int traverseType) {
switch (traverseType) {
case 1:
System.out.print("\nPreorder traversal: ");
// call preOrder(root) and implement preOrder()
preOrder(root);
break;
case 2:
System.out.print("\nList of all students: ");
inOrder(root);
break;
case 3:
System.out.print("\nPostorder traversal: ");
// call postOrder(root) and implement postOrder()
postOrder(root);
break;
}
System.out.println();
}
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element.getId() + " ");
inOrder(localRoot.right);
}
}
private void preOrder(Node localRoot) {
if (localRoot != null) {
System.out.print(localRoot.element + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
private void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.element + " ");
}
}
}
class Node {
protected Student element;
protected Node left;
protected Node right;
public Node(Student st) {
element = st;
}
}
The issue is that you are trying to see if a LinkedList of type Course contains a String. The contains method for LinkedList takes an Object as it's parameter type and that is why you are not getting a compilation issue.
The below code snippet is never true because a Course will never equal a String. I mention equal here because internally the LinkedList contains method checks equality for the Object you pass in against the Objects it contains.
if(n.element.returnList().contains(course)) {
System.out.print(n.element.getId() + " ");
}
Possible Solution using Map
Change courses to be a Map in Student class and then change the IF statement to check if the Map contains an element based on the course name. If the Map contains an object then it's true that the Student takes this course.
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
Map<String, Course> courses = new HashMap<>();
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(Course course) {
courses.put(course.getId(), course);
}
public Map<String, Course> getCourses() {
return courses;
}
}
IF statement
if(n.element.getCourses().get(course) != null) {
System.out.print(n.element.getId() + " ");
}
Possible Solution using List
Add new method to Student class.
public boolean takesCourse(String courseName){
for(Course course : courses){
if(courseName.equals(course.getId)) {
return true;
}
}
return false;
}
IF statement
if(n.element.takesCourse(course)) {
System.out.print(n.element.getId() + " ");
}

Binary Search Tree find method returning not found

This is a homework assignment i'm working on and I'm having a little trouble with it. I've implemented my own version of a binary search tree rather than using JDK. I'm inserting multiple student objects into the binary search tree in terms of the student's ID, which is a type string. I'm not getting any compile errors but the program keeps returning that the value is not found when it should be the fourth student that was inserted into the tree. I've implemented all of the find methods already, but not sure where I'm going wrong with them, since the output should be saying that the value was found.
Output:
run:
11114 not found
BUILD SUCCESSFUL (total time: 0 seconds)
Homework5.class / main:
package homework5;
import java.util.LinkedList;
public class Homework5 {
static Roster rost = new Roster();
public static void main(String[] args) {
addStudent();
lookupStudent("11114");
}
// add students to the roster
static void addStudent() {
rost.addStudent(new Student("11111", "Jon", "Benson"));
rost.addStudent(new Student("11112", "Erick", "Hooper"));
rost.addStudent(new Student("11113", "Sam", "Shultz"));
rost.addStudent(new Student("11114", "Trent", "Black"));
rost.addStudent(new Student("11115", "Michell", "Waters"));
rost.addStudent(new Student("11116", "Kevin", "Johnson"));
}
// lookup a student in the roster
static void lookupStudent(String id) {
if (rost.find(id) != null) {
System.out.println(id + " found");
} else {
System.out.println(id + " not found");
}
}
}
Student.class
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(String id) {
LinkedList list = new LinkedList();
list.add(id);
}
}
Roster.class
class Roster {
Student root;
int numStudents;
BST<Student> roster = new BST<>();
public Roster() {
root = null;
numStudents = 0;
}
public void addStudent(Student st) {
roster.insert(st);
numStudents++;
}
public Student find(String id) {
roster.find(id);
return null;
}
BST.java
package homework5;
class BST<Roster extends Comparable> {
private Node root;
public BST() {
root = null;
}
// Generic find method
public Node find(String id) {
Node current = root;
while (id.compareTo(current.element.getId()) != 0) {
if (id.compareTo(current.element.getId()) < 0) {
current = current.left;
}
else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current;
}
public void insert(Student st) {
Node newNode = new Node(st);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (st.compareTo(current.element) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
// Recursive method - traverse generic BST
// While root is not equal to null visit left node and print value
// of root, then visit right node. Repeat until root becomes null
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element + " ");
inOrder(localRoot.right);
}
}
}
class Node {
protected Student element;
protected Node left;
protected Node right;
public Node(Student st) {
element = st;
}
}
Roster.find() always returns null.
Change it to
public Student find(String id) {
return roster.find(id).element;
}
your code looks fine... a few misconceptions like the comments suggested, just change those couple of lines
public Student find(String id) {
return roster.find(id);
}
and return current.element from roster.find() change the signature to public Student find(String id)
Note: keep in mind this will effect the generic property of the code, a better approach is to implement node as a generic data container e.g Node<Student> make roster.find() return a Node object and get the data from the node so you can return Student object at the end
or at least change only this function instead (it's a better solution than mine)
public Student find(String id) {
return roster.find(id).element;
}

How to pass node as a parameter

I have a custom linked list that has node objects of class Student. There are two recursive methods called countNodesRec(Node list) & worstStudentRec(Node List) that both need node object as a parameter.
list1.worstStudentRec(?????)
list1.countNodesRec(????)
Parameters I tried already that have given me errors
list1.list
list1
Not sure what to put there, please help!
Test Class
public class TestList {
public static void main(String[] args) {
Student s1 = new Student("Adams", 3.9, 26);
Student s2 = new Student("Lewis", 2.1, 29);
Student s3 = new Student("Lopez", 4.0, 53);
Student s4 = new Student("Smith", 3.2, 22);
Student s5 = new Student("Zeeler", 3.6, 38);
LinkedList list1 = new LinkedList();
LinkedList list2 = new LinkedList();
LinkedList list3 = new LinkedList();
//1
list1.addFront(s1);
list1.addFront(s2);
list1.addFront(s3);
list1.addFront(s4);
list1.addFront(s5);
list1.printLinkedList();
System.out.println("Worst Student" + list1.worstStudentRec());
System.out.println("Number of Students" + list1.countNodesRec());
}
}
Student Class
public class Student
{
private String lastName;
private double gpa;
private int age;
public Student(String lastName, double gpa, int age)
{
this.lastName = lastName;
this.gpa = gpa;
this.age = age;
}
public int compareTo(Student s)
{
if (gpa < s.gpa)
{
return -1;
}
else if (gpa > s.gpa)
{
return 1;
}
else
{
return 0;
}
}
public String toString()
{
return lastName + "\t" + gpa + "\t" + age;
}
public double getGpa()
{
return gpa;
}
}
Linked List Class
public class LinkedList
{
private class Node
{
public Student data;
public Node next;
public Node(Student s)
{
data = s;
next = null;
}
}
private Node list;
public LinkedList()
{
list = null;
}
public Student bestStudent()
{
Student bestStudent, bstStu;
Node current;
if (list == null)
{
return bestStudent = null;
}
else
{
current = list;
bstStu = new Student("", 0.00, 0);
while (current != null)
{
if (bstStu.getGpa() <= current.data.getGpa())
{
bstStu = current.data;
}
current = current.next;
}
bestStudent = bstStu;
}
return bestStudent;
}
public int countNodesRec(Node list)
{
if(list == null)
{
return 0;
}
else
{
return 1 + countNodesRec(list.next);
}
}
public Student worstStudentRec(Node list)
{
if (list == null)
{
return null;
}
else if (list.next == null)
{
return list.data;
}
Student worstStudent = worstStudentRec(list.next);
return (list.data.compareTo(worstStudent) <= 0) ? list.data : worstStudent;
}
}
You can create a getList method in Linked List class, then call the method in main:
list1.worstStudentRec(list1.getList ())
list1.countNodesRec(list1.getList ())

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.

QuickSort using Linked List

I need help with this code. I need to call the quicksort method without any parameters in the main method. But this program has a parameter. How can I make it work and not have any parameter when calling it in the main method?
Please help.
Employee Class
public class Employee
{
private String firstname;
private int idNumber;
private String lastname;
Employee(String lname,String fname, int id)
{
lastname = lname;
firstname = fname;
idNumber = id;
}
public void setLastName(String lname)
{lastname = lname;}
public String getLastName()
{return lastname;}
public void setFirstName(String fname)
{firstname = fname;}
public String getFirstName()
{return firstname;}
public void setidNumber(int id)
{idNumber = id;}
public int getidNumber()
{return idNumber;}
public String toString()
{
String str = "\nName: " + lastname + " " + firstname
+ "\nID: " + idNumber;
return str;
}
public int compareTo(Employee Employee2)
{
int diff = lastname.compareToIgnoreCase(Employee2.getLastName());
if(diff != 0)
return diff;
else
return -1;
}
}
Linked List Class
public class DoublyLinkedList
{
public class DoublyLinkedListLink
{
public Employee info;
public DoublyLinkedListLink next;
public DoublyLinkedListLink back;
//Default Constructor
//Postcondition: info = 0;
// next = null; back = null;
public DoublyLinkedListLink()
{
info = null;
next = null;
back = null;
}
public DoublyLinkedListLink(Employee item)
{
info = item;
next = null;
back = null;
}
public void displayInfo()
{
System.out.print(info + " ");
}
}
protected int count;
protected DoublyLinkedListLink first;
protected DoublyLinkedListLink last;
public DoublyLinkedList()
{
first = null;
last = null;
count = 0;
}
public void initializeList()
{
first = null;
last = null;
count = 0;
}
public boolean isEmpty()
{
return (first == null);
}
public int length()
{
return count;
}
public void print()
{
DoublyLinkedListLink current = first;
while (current != null)
{
current.displayInfo();
current = current.next;
}//end while
}//end print
public void insert(Employee insertItem)
{
DoublyLinkedListLink newNode = new DoublyLinkedListLink(insertItem);
if (isEmpty())
{
first = newNode;
last = newNode;
count++;
}
else
{
last.next = newNode;
newNode.back = last;
}
last = newNode;
}
public DoublyLinkedListLink partition(DoublyLinkedList list, DoublyLinkedListLink first, DoublyLinkedListLink last)
{
DoublyLinkedListLink smallIndex = first;
DoublyLinkedListLink index = smallIndex.next;
DoublyLinkedListLink temp = new DoublyLinkedListLink();
Employee pivot = first.info;
while (index != last.next)
{
if((index.info).compareTo(pivot) <= 0)
{
smallIndex = smallIndex.next;
temp.info = index.info;
index.info = smallIndex.info;
smallIndex.info = temp.info;
}
index = index.next;
}
temp.info = first.info;
first.info = smallIndex.info;
smallIndex.info = temp.info;
System.out.print("The list in partition is: "); list.print();
System.out.print("\n");
return smallIndex;
}
private void recQuickSort(DoublyLinkedList list, DoublyLinkedListLink first, DoublyLinkedListLink last)
{
while(first != last)
{
DoublyLinkedListLink pivotLocation = partition(list, first, last);
recQuickSort(list, first, pivotLocation.back);
recQuickSort(list, pivotLocation.next, last);
}
}
public void quickSort(DoublyLinkedList list)
{
recQuickSort(list, list.first, list.last);
}
}
Main Method
class MergeSortDriver
{
public static void main (String [] args)
{
Employee e1 = new Employee("Grey","Bob",5239);
Employee e2 = new Employee("Smith","Maggie", 9845);
Employee e3 = new Employee("Ocasio","John", 8502);
Employee e4 = new Employee("Yang", "Christina", 4656);
Employee e5 = new Employee("Carpenter","Kimberely", 6798);
Employee e6 = new Employee("Aguilar","Charlie", 5986);
DoublyLinkedList a = new DoublyLinkedList();
Employee A[] = {e1,e2,e3,e4,e5,e6};
a.insert(e1);
a.insert(e2);
a.insert(e3);
a.insert(e4);
a.insert(e5);
a.insert(e6);
a.print();
a.quickSort();
a.print();
}
}
Use this instead of the parameter. Instead of:
public void quickSort(DoublyLinkedList list)
{
recQuickSort(list, list.first, list.last);
}
You can do
public void quickSort()
{
recQuickSort(this, this.first, this.last);
}
This way you are using the instance you are invoking quickSort on, instead of one passed into the quickSort method.
EDIT - Regarding the error mentioned in comments:
The NullPointerException does not have anything to do with whether you use this instead of a parameter. Instead I suspect it has something to do with your while loop around the recursive calls.
while(first != last)
{
DoublyLinkedListLink pivotLocation = partition(list, first, last);
recQuickSort(list, first, pivotLocation.back);
recQuickSort(list, pivotLocation.next, last);
}
Such a while-loop is usually not needed in a recursive solution. You can (kinda) think of your recursion as your loop. So instead of a loop, you should restrict the calls with ifs. It could look something like:
DoublyLinkedListLink pivot = partition(list, first, last);
if(first != pivot && first != pivot.back) {
recQuickSort(list, first, pivot.back);
}
if(last != pivot && last != pivot.next) {
recQuickSort(list, pivot.next, last);
}
Furthermore, you should handle the case when the list is empty. In this case partition will throw a NullPointerException because both first and last would be null.
I would think that fixing these two things would make it work. However, I have not tested it.
Also, try to keep code nicely formatted. Code without consistent formatting (such as indentation) is a pain to work with and look at.

Categories