0% found this document useful (0 votes)
11 views24 pages

Java Stack Implementation with Books

The document outlines exercises to implement a Stack data structure in Java using both ArrayList and LinkedList. It includes the definition of a Book class with attributes and methods, and a Stack class that manages a collection of Book objects with various functionalities like push, pop, search, and display. Additionally, it provides a CD class and a corresponding Stack implementation for managing CDs, demonstrating the use of linked structures for stack operations.

Uploaded by

Full name
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views24 pages

Java Stack Implementation with Books

The document outlines exercises to implement a Stack data structure in Java using both ArrayList and LinkedList. It includes the definition of a Book class with attributes and methods, and a Stack class that manages a collection of Book objects with various functionalities like push, pop, search, and display. Additionally, it provides a CD class and a corresponding Stack implementation for managing CDs, demonstrating the use of linked structures for stack operations.

Uploaded by

Full name
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exercises: Stack

Exercise 1: Write a java program to implement a Stack using [Link]


with the following:
- Class Book with private attributes (title, author, pages).
- Add 2 constructors and getters and setters to Book class beside toString
- Class Stack with attributes and methods (push, pop, peek, search(by
title), size and printAll) using ArrayList<Book>.
- Add method empty to return is the stack empty or not
- Add method clear to empty the stack
- The method search should return the position of first found book
- Add method searchforBook (by title) that return the author name for
the found book.
- Add method searchAll (by author) that returns all positions of books
written by an author.
- Class main to create a shelf as Stack object and add Books using the
stack’s methods above.
- Print all data in Stack using printAll method and tostring
NB: The top of stack is the beginnig of ArrayList

public class Book {


private String title;
private String author;
private int pages;

public Book() { }

1
public Book(String title, String author, int pages) {
[Link] = title;
[Link] = author;
[Link] = pages; }
public String getTitle() {
return title;
}
public void setTitle(String title) {
[Link] = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
[Link] = author;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
[Link] = pages;
}
@Override
public String toString() {
return "Book{" + "title=" + title +
", author=" + author +
", pages=" + pages + '}';
}

}
2
import [Link];

public class Stack {

private ArrayList<Book> booklist;


private int top = 0;

public Stack() {
booklist = new ArrayList<>();
}

public void push(Book b) {


[Link](top, b);
}

public Book peek() {


if (![Link]()) {
return [Link](top);
}
return null;
}

public Book pop() {


Book hold = null;
if (![Link]()) {
hold = [Link](top);
[Link](top);
return hold;
}
return hold;
}
3
public int size() {
return [Link]();
}

public int search(String title) {


int counter = 0;
for (Book b : booklist) {
counter++;
if ([Link]().equals(title)) {
return counter;
}
}
return 0;
}

public ArrayList<Integer> searchAll(String author) {


ArrayList<Integer> counters = new ArrayList<>();
int counter = 0;
for (Book b : booklist) {
counter++;
if ([Link]().equals(author)) {
[Link](counter);
}
}
return counters;
}

4
public String searchforBook(String title) {
Book counter = null;
for (Book b : booklist) {
if ([Link]().equals(title)) {
return [Link]();
}
}
return null;
}
public boolean empty() {
return [Link]();
}

public void clear() {


[Link]();
}

public void PrintAll() {


for (Book book : booklist) {
[Link]("title is " + [Link]());
[Link]("Author is " + [Link]());
}
}

public void display() {


for (Book book : booklist) {
[Link]([Link]());
}
}
}
5
import [Link];

public class Book_stack_arrayList {

public static void main(String[] args) {

Book b1 = new Book("Learn Java", "Samir", 200);


Book b2 = new Book("Learn python", "Samir", 300);
Book b3 = new Book("Learn c++", "Samira", 2000);

Stack shelf = new Stack();

[Link](b1);
[Link](b2);
[Link](b3);

[Link]("turn is for book " + [Link]());

[Link]();
[Link]();

int pythonposition = [Link]("Learn python");

if (pythonposition > 0) {
[Link]("The position of python book is "
+ pythonposition);
} else {
[Link]("python book isn't in stack");
}

6
[Link]();

ArrayList<Integer> positions_of_samir_books =
[Link]("Samir");

if (!positions_of_samir_books.isEmpty()) {
[Link]("The positions of Samir's books are:");
for (int pos : positions_of_samir_books) {
[Link](pos + " ");
}
} else {
[Link]("Samir hasn't any book");
}
[Link]();
[Link]();
[Link]();

Book last = [Link]();


[Link]();
[Link]("Last element " + [Link]());

[Link]();
[Link]("the stack is empty?: " + [Link]());
[Link]();
[Link]("the stack is empty now?: " + [Link]());

}
}

7
Output:

turn is for book Book{title=Learn c++, author=Samira, pages=2000}

Book{title=Learn Java, author=Samir, pages=200}


Book{title=Learn python, author=Samir, pages=300}
Book{title=Learn c++, author=Samira, pages=2000}

title is Learn Java


Author is Samir
title is Learn python
Author is Samir
title is Learn c++
Author is Samira

The position of python book is 2

The positions of Samir's books are: 1 2

Book{title=Learn Java, author=Samir, pages=200}


Book{title=Learn python, author=Samir, pages=300}

Last element Learn python

Book{title=Learn Java, author=Samir, pages=200}

the stack is empty?: false


the stack is empty now?: true

8
Exercise 2: Write a java program to implement a Stack using
[Link] with the following:
- Class Book with private attributes (title, author, pages).
- Add 2 constructors and getters and setters to Book class beside toString
- Class Stack with attributes and methods (push, pop, peek, search(by
title), size and printAll) using LinkedList<Book>.
- Add method empty to return is the stack empty or not
- Add method clear to empty the stack
- The method search should return the position of first found book
- Add method searchforBook (by title) that return the author name for
the found book.
- Add method searchAll (by author) that returns all positions of books
written by an author.
- Class main to create a shelf as Stack object and add Books using the
stack’s methods above.
- Print all data in Stack using printAll method and tostring
NB: The top of stack is the end of LinkedList

public class Book {


private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
[Link] = title;
[Link] = author;
[Link] = pages;
}
9
public Book() { }

public String getTitle() {


return title;
}
public void setTitle(String title) {
[Link] = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
[Link] = author;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
[Link] = pages;
}
@Override
public String toString() {
return "Book{" + "title=" + title +
", author=" + author +
", pages=" + pages + '}';
}

10
import [Link];
import [Link];

public class Stack {

private LinkedList<Book> booklist;


private int top;

public Stack() {
booklist = new LinkedList<>();
top = 0;
}

public void push(Book b) {


[Link](b);
}

public Book peek() {


if (![Link]()) {
return [Link]();
}
return null;
}

public Book pop() {


Book hold = null;
if (![Link]()) {
hold = [Link]();
[Link]();
return hold;
11
}
return hold;
}

public int size() {


return [Link]();
}

public int search(String title) {


for (int i = [Link]() - 1; i >= 0; i--) {
Book b = [Link](i);
if ([Link]().equals(title)) {
return i + 1;
}
}
return 0;
}

public ArrayList<Integer> searchAll(String author) {


ArrayList<Integer> counters = new ArrayList<>();
for (int i = [Link]() - 1; i >= 0; i--) {
Book b = [Link](i);
if ([Link]().equals(author)) {
[Link](0, i + 1);
}
}
return counters;
}

12
public String searchforBook(String title) {
for (int i = [Link]() - 1; i >= 0; i--) {
Book b = [Link](i);
if ([Link]().equals(title)) {
return [Link]();
}
}
return null;
}

public boolean empty() {


return [Link]();
}
public void clear() {
[Link]();
}

public void PrintAll() {


for (int i = [Link]() - 1; i >= 0; i--) {
Book book = [Link](i);
[Link]("title is " + [Link]());
[Link]("Author is " + [Link]());
}
}
public void display() {
for (int i = [Link]() - 1; i >= 0; i--) {
[Link]([Link](i).toString());
}
}
}
13
import [Link];

public class Bookstack_linked_end {


public static void main(String[] args) {

Book b1 = new Book("Learn Java", "Samir", 200);


Book b2 = new Book("Learn python", "Samir", 300);
Book b3 = new Book("Learn c++", "Samira", 2000);

Stack shelf = new Stack();

[Link](b1);
[Link](b2);
[Link](b3);

[Link]("turn is for book " + [Link]());

[Link]();
[Link]();

int pythonposition = [Link]("Learn python");

if (pythonposition > 0) {
[Link]("The position of python book is "
+ pythonposition);
} else {
[Link]("python book isn't in stack");
}

[Link]();
14
ArrayList<Integer> positions_of_samir_books =
[Link]("Samir");

if (!positions_of_samir_books.isEmpty()) {
[Link]("The positions of Samir's books are: ");
for (int pos : positions_of_samir_books) {
[Link](pos + " ");
}
} else {
[Link]("Samir hasn't any book");
}

[Link]();
[Link]();
[Link]();

Book last = [Link]();

[Link]();
[Link]("Last element " + [Link]());

[Link]();

[Link]("the stack is empty?: " + [Link]());


[Link]();
[Link]("the stack is empty now?: " + [Link]());

}
}
15
Output:

turn is for book Book{title=Learn c++, author=Samira, pages=2000}

Book{title=Learn c++, author=Samira, pages=2000}


Book{title=Learn python, author=Samir, pages=300}
Book{title=Learn Java, author=Samir, pages=200}

title is Learn c++


Author is Samira
title is Learn python
Author is Samir
title is Learn Java
Author is Samir

The position of python book is 2

The positions of Samir's books are: 1 2

Book{title=Learn python, author=Samir, pages=300}


Book{title=Learn Java, author=Samir, pages=200}

Last element Learn python

Book{title=Learn Java, author=Samir, pages=200}

the stack is empty?: false


the stack is empty now?: true

16
Exercise 1: Write a java program to implement a Stack using the
implementation of the algorithm with the following:
- Class CD with private attributes (title, singer, size) and next CD.
- Add 2 constructors and getters and setters to CD class beside toString
- Class Stack with attributes and methods (push, pop, peek, search(by
title), size and printAll).
- The method search should return the position of first found CD
- Class main to create a cdstack as Stack object and add CDs using the
stack’s methods above.
- Print all data in Stack using printAll method and tostring
NB: The top of stack is the head of LinkedList

public class CD {

private String title;


private String singer;
private int size;
CD next;

public CD() {
}

public CD(String title, String singer, int size) {


[Link] = title;
[Link] = singer;
[Link] = size;
}

17
public String getTitle() {
return title;
}

public void setTitle(String title) {


[Link] = title;
}

public String getSinger() {


return singer;
}

public void setSinger(String singer) {


[Link] = singer;
}

public int getSize() {


return size;
}

public void setSize(int size) {


[Link] = size;
}
@Override
public String toString() {
return "CD{" + "title=" + title
+ ", singer=" + singer
+ ", size=" + size + '}';
}
}
18
public class Stack {

private CD top;

public Stack() {
top = null;
}

public void push(CD cd) {


if (top == null) {
top = cd;
} else {
[Link] = top;
top = cd;
}
}

public CD peek() {
return top;
}

public CD pop() {
CD hold = top;
top = [Link];
return hold;
}

public boolean empty() {


// first method
// return top==null;
19
// second method
if (top == null) {
return true;
} else {
return false;
}
}

public void clear() {


top = null;
}

public int search(String singer) {


int counter = 0;
CD temp = top;
while (temp != null) {
counter++;
if ([Link]().equals(singer)) {
return counter;
}
temp = [Link];
}
return 0;
}

public void display() {


CD temp = top;
while (temp != null) {
[Link]([Link]());
temp = [Link]; }
}
20
public void printALL() {
CD temp = top;
while (temp != null) {
[Link]("CD title is " + [Link]());
[Link]("Singer is " + [Link]());
temp = [Link];
}
}
}

21
public class CD_stack_implemm {
public static void main(String[] args) {

Stack cdstack = new Stack();

CD c1 = new CD("title1", "Samira", 700);


CD c2 = new CD("title2", "Samira", 600);
CD c3 = new CD("title3", "Samir", 400);

[Link](c1);
[Link](c2);
[Link](c3);

[Link]();
[Link]();
[Link]();

[Link]("Cd of samira is found at position: "


+ [Link]("Samira"));

[Link]();

[Link]("After pop");
[Link]();

[Link]("turn of cd title: "


+ [Link]().getTitle());
[Link]();

22
[Link]();
[Link]();

[Link]("the turn of cd with remove"


+ [Link]());
[Link]();

[Link]();

}
}

23
Output:

CD title is title3
Singer is Samir
CD title is title2
Singer is Samira
CD title is title1
Singer is Samira

CD{title=title3, singer=Samir, size=400}


CD{title=title2, singer=Samira, size=600}
CD{title=title1, singer=Samira, size=700}

Cd of samira is found at position: 2

After pop
CD{title=title2, singer=Samira, size=600}
CD{title=title1, singer=Samira, size=700}
turn of cd title: title2

CD title is title2
Singer is Samira
CD title is title1
Singer is Samira

the turn of cd with removeCD{title=title2, singer=Samira, size=600}

CD{title=title1, singer=Samira, size=700}

24

Common questions

Powered by AI

Designing a stack as an abstract data type emphasizes encapsulation and modularity in its implementation. This permits the creation of abstract methods like push, pop, peek, and search, independent of the underlying data structure, be it an ArrayList or LinkedList . By treating stack operations abstractly, the Stack class can provide a consistent interface and behavior while allowing internal changes to optimize performance or storage without affecting the consumer of the Stack class .

An ArrayList-based stack implementation may suffer performance issues with frequently changing stack sizes due to the need for dynamic resizing, especially when elements are frequently pushed or popped, as this may require shifting elements. Conversely, a LinkedList-based stack offers more efficient resizing with constant time complexity for additions or removals at the ends, resulting in better performance for stacks with frequent size changes . This also translates into memory usage differences, as LinkedLists incur overhead for node storage, which might be compensated by ArrayList's contiguous memory use .

Using a fixed initial index in search methods can lead to logical errors, such as returning incorrect positions by not accounting for the zero-based or one-based index differences inherent in array and list operations. It may also lead to inconsistency in results when comparing searches by title and author, causing confusion between `found` and `not found` results in searchAll or searchForBook methods . To address this, index handling needs careful adjustment to align with array characteristics and ensure accurate position reporting .

The clear method directly affects memory management by removing references to all elements in the stack, thereby allowing the garbage collector to reclaim memory occupied by those elements . On the other hand, the empty method simply checks if the stack is empty without altering the stack itself, making it a more cautious operation with no direct impact on memory until elements are explicitly removed . Proper use of these methods ensures efficient memory handling and availability of resources in Java applications .

The toString method is crucial for debugging as it provides a string representation of an object's state, facilitating human-readable output of stack operations. In the exercises, the toString method outputs the essential attributes (e.g., title, author, pages) of a Book or CD, enabling a clearer understanding of the stack's contents at any point . This is especially useful for tracking the state evolution during pushes and pops, thus aiding in the verification and debugging of complex stack operations or logic errors .

Both the ArrayList and LinkedList implementations for the Book stack provide similar methods for pushing, popping, and peeking at elements, as well as searching by title and author. The difference lies in the management of the stack's top: for ArrayList, the top is treated as the beginning of the list, while for LinkedList, it is treated as the end of the list . Additionally, performance considerations differ; LinkedLists might be more efficient for inserting and removing elements at the end due to constant time complexity, while ArrayLists might be slower due to needing to shift elements .

In both the Book and CD Stack implementations, the 'peek' method allows viewing the top element without altering the stack's state, providing a non-destructive view of the stack's contents. Conversely, the 'pop' method removes the top element, decreasing the stack's size and altering its state. These methods encapsulate common stack operations but differ in how they interact with the stack's content and state, reinforcing object-oriented design principles by separating concerns .

The @Override annotation communicates to the developer and the Java compiler that the method is intended to override a method from a superclass. This provides compile-time checking to ensure the method signature matches a declared superclass method, reducing errors and making code maintenance easier. In the Book and CD classes, it ensures that the toString methods correctly override the Object's toString method, enhancing readability and debugging .

The method 'searchforBook' returns null because the implementation tries to return the 'getAuthor()' method on an uninitialized Book variable named counter, which is always null. Therefore, even if a book with the specified title exists, the method cannot return a proper author name due to this logical flaw .

Using the LinkedList's getLast method when the list is empty will result in a NoSuchElementException since there's no check to ensure the list isn't empty before accessing the last element . To prevent this, it is crucial to check if the stack is empty beforehand, using the empty method, to avoid runtime exceptions and ensure program stability .

You might also like