Question

re-implement the Bookshelf class using a linkedlist and a Node class. Implement the above add, remove,...

re-implement the Bookshelf class using a linkedlist and a Node class. Implement the above add, remove, and search methods again.
here is the code for that:


public class Book {
  
private String title;
private double price;
  
public Book()
{
title="";
price=0;
}
  
public Book(String title, double price)
{
this.title = title;
this.price = price;
}
  
public void setTitle(String title)
{
this.title = title;
}
  
public void setPrice(double price)
{
this.price = price;
}
  
public String getTitle()
{
return title;
}
  
public double getPrice()
{
return price;
}
  
public boolean equals(Book book)
{
// if both title and price of both books are same
if((title.equalsIgnoreCase(book.title)) && (price == book.price))
return true;
return false;
}
  
public String toString()
{
return title+" : "+price;
}
}
//end of Book.java
//BookShelf.java : Java program to implement BookShelf using array
public class BookShelf {
  
private Book books[];
private int size;
  
public BookShelf(int capacity)
{
books = new Book[capacity];
size=0;
}
  
public int getSize()
{
return size;
}
  
public boolean addBook(Book book)
{
if(size < books.length)
{
books[size] = book;
size++;
return true;
}
return false;
}
  
public boolean removeBook(Book book)
{
for(int i=0;i<size;i++)
{
if(books[i].equals(book))
{
for(int j=i;j<size-1;j++)
books[j] = books[j+1];
size--;
return true;
}
}
  
return false;
}
  
public boolean searchBook(Book book)
{
for(int i=0;i<size;i++)
{
if(books[i].equals(book))
{
return true;
}
}
  
return false;
}
  
public String toString()
{
String booksStr = "";
for(int i=0;i<size;i++)
{
booksStr += books[i].toString()+"\n";
}
  
return booksStr;
}
public static void main(String args[])
{
BookShelf bookShelf = new BookShelf(10); // create a bookshelf object
// create 5 books and add them to bookshelf
Book book1 = new Book("Title1",20);
bookShelf.addBook(book1);
book1 = new Book("Title2",25);
bookShelf.addBook(book1);
book1 = new Book ("Title3",15);
bookShelf.addBook(book1);
book1 = new Book ("Title4",32.5);
bookShelf.addBook(book1);
book1 = new Book ("Title5",25);
bookShelf.addBook(book1);
  
System.out.println(bookShelf);
}
}
//end of BookShelf.java
0 0
Add a comment Improve this question Transcribed image text
Answer #1
/**
 * Please find the required solution
 */

// Node class with book and ref to second book
class Node {
    Book book;
    Node next;

    // constructor
    public Node(Book book) {
        this.book = book;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

//BookShelf.java : Java program to implement BookShelf using LinkedList
public class BookShelf {

    private Node headNode;
    private int size;
    private int capacity;

    public BookShelf(int capacity) {
        this.capacity = capacity;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean addBook(Book book) {
        if (size < capacity) {
            Node node = new Node(book);
            if (headNode == null)
                headNode = node;
            else {
                Node lastNode = headNode;
                while (lastNode.next != null) {
                    lastNode = lastNode.next;
                }
                lastNode.next = node;
            }
            size++;
            return true;
        }
        return false;
    }

    public boolean removeBook(Book book) {
        if (headNode.book.equals(book)) {
            headNode = headNode.next;
        }
        Node currNode = headNode, prev = null;
        while (currNode != null && currNode.book.equals(book)) {
            prev = currNode;
            currNode = currNode.next;
        }
        if (currNode != null) {
            prev.next = currNode.next;
            size--;
            return true;
        }
        return false;
    }

    public boolean searchBook(Book book) {

        Node lastNode = headNode;
        while (lastNode != null) {
            if (lastNode.book.equals(book))
                return true;
            lastNode = lastNode.next;
        }

        return false;
    }

    public String toString() {
        String booksStr = "";

        Node lastNode = headNode;
        while (lastNode != null) {
            booksStr += lastNode.book.toString() + "\n";
            lastNode = lastNode.next;
        }

        return booksStr;
    }

    public static void main(String args[]) {
        BookShelf bookShelf = new BookShelf(10); // create a bookshelf object
// create 5 books and add them to bookshelf
        Book book1 = new Book("Title1", 20);
        bookShelf.addBook(book1);
        book1 = new Book("Title2", 25);
        bookShelf.addBook(book1);
        book1 = new Book("Title3", 15);
        bookShelf.addBook(book1);
        book1 = new Book("Title4", 32.5);
        bookShelf.addBook(book1);
        book1 = new Book("Title5", 25);
        bookShelf.addBook(book1);

        System.out.println(bookShelf);
    }
}
//end of BookShelf.java 

Sample output:

Add a comment
Answer #2

// Linked List version of BookShelf
public class BookShelfLL {

    private Node head; // head of the BookShelf
    private int size; // Size of the BookShelf

    class Node {
        private Book data;
        private Node link;

        Node(Book book) {
            data = book;
            // link by default points to null
        }
    }

    public BookShelfLL() {
        head = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean addBook(Book book) {

        Node newBook = new Node(book);

        if (newBook == null) {
            // Heap Overflow
            return false;
        }

        // Case : Linked List is Empty
        if (head == null) {
            head = newBook;
            size++;
        } else {
            // Traverse till the last node and add new Book there
            Node iterator = head;
            while (iterator.link != null) {
                iterator = iterator.link;
            }
            iterator.link = newBook;
            size++;
        }
        return true;
    }

    public boolean removeBook(Book book) {

        Node iterator = head;

        // Case A : The head is the book being searched
        if (iterator != null && iterator.data.equals(book)) {
            head = head.link;
            size--;
            return true;
        }

        // Case B : The book bein searched lies in a node other than head
        Node previous = null;
        while (iterator != null && !iterator.data.equals(book)) {
            previous = iterator;
            iterator = iterator.link;
        }


        // If the Book was present, it should be at iterator's current data
        // Therefore the iterator shall not be null
        if (iterator != null) {
            // Unlink the current Node
            previous.link = iterator.link;
            size--;
            return true;
        }

        // Case C : Book not present
        return false;
    }

    public boolean searchBook(Book book) {

        Node iterator = head;
        while (iterator != null && !iterator.data.equals(book)) {
            iterator = iterator.link;
        }

        // iterator will be null if Book not present
        return iterator != null;
    }

    public String toString() {
        String booksStr = "";
        Node iterator = head;
        while (iterator != null) {
            booksStr += iterator.data.toString() + "\n";
            iterator = iterator.link;
        }

        return booksStr;
    }

    public static void main(String args[]) {
        // Linked List version of BookShelf will have infinite capacity (The Limit of Heap)
        BookShelfLL bookShelf = new BookShelfLL(); // create a bookshelf object
        // create 5 books and add them to bookshelf
        Book book1 = new Book("Title1", 20);
        bookShelf.addBook(book1);
        Book book2 = new Book("Title2", 25);
        bookShelf.addBook(book2);
        book1 = new Book("Title3", 15);
        bookShelf.addBook(book1);
        book1 = new Book("Title4", 32.5);
        bookShelf.addBook(book1);
        book1 = new Book("Title5", 25);
        bookShelf.addBook(book1);

        System.out.println(bookShelf);

        // Remove Title2
        System.out.println(bookShelf.removeBook(book2));
        System.out.println("After removal");
        System.out.println(bookShelf);

        // Search Title5
        System.out.println(bookShelf.searchBook(book1));
    }
}

Add a comment
Know the answer?
Add Answer to:
re-implement the Bookshelf class using a linkedlist and a Node class. Implement the above add, remove,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Write an equals method for the Shirt class provided below. Two shirts are logically equivalent if...

    Write an equals method for the Shirt class provided below. Two shirts are logically equivalent if they have the same size, color, and price. public class Shirt { private Size size; private String color; private double price; enum Size { SMALL, MEDIUM, LARGE } public Shirt(Size size, String color, double price) { this.size = size; this.color = color; this.price = price; } public Size getSize() { return size; } public String getColor() { return color; } public double getPrice() {...

  • public enum Rating {               GENERAL(0),        PARENTALGUIDANCE(1),        MATURE(2);     

    public enum Rating {               GENERAL(0),        PARENTALGUIDANCE(1),        MATURE(2);               private int minAge;               private Rating(int i)        {              minAge = i;        }               public int getMinAge()        {              return minAge;        }               public void setMinAge(int age)        {              minAge = age;        }               public String toString()        {              switch(this)              {              case GENERAL:                     return "G";              case PARENTALGUIDANCE:                     return "P";              case MATURE:                     return...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Design and implement a Java data structure class named BookShelf which has an array to store...

    Design and implement a Java data structure class named BookShelf which has an array to store books and the size data member. The class should have suitable constructors, get/set methods, and the toString method, as well as methods for people to add a book, remove a book, and search for a book. Design and implement a Java class named Book with two data members: title and price. Test the two classes by creating a bookshelf object and five book objects....

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

  • Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The...

    Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The clone method must allow a deep copy on the students field. In addition, add the equals(Object o) and the toString() methods. Write a test program to invoke the compareTo, clone, equals, and toString methods in a meaningful way. Below is the Listing from the book that needs to be rewritten public class Course {    private String courseName;    private String[] students = new...

  • Please implement a right rotation funtion: private Node rightRotate(Node root) { } Remember to return the...

    Please implement a right rotation funtion: private Node rightRotate(Node root) { } Remember to return the new root of the subtree to the parent so the parent can set it to be its child package trees; public class BinaryTree> { private Node root; //private int size; public static int sumTree(Node root) { if(root== null) { return 0; } int center = 0; if( root.item % 2 == 0) { center = root.item; } int left = sumTree(root.left); int right =...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT