0% found this document useful (0 votes)
28 views3 pages

Java Book Stack Implementation

The document defines a simple stack implementation using a linked list in Java, where each node represents a book with attributes like title, price, edition, and pages. It includes methods to push, pop, and peek at the top book in the stack. The main class demonstrates pushing five books onto the stack, peeking at the top book, popping two books, and displaying the remaining books in the stack.

Uploaded by

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

Java Book Stack Implementation

The document defines a simple stack implementation using a linked list in Java, where each node represents a book with attributes like title, price, edition, and pages. It includes methods to push, pop, and peek at the top book in the stack. The main class demonstrates pushing five books onto the stack, peeking at the top book, popping two books, and displaying the remaining books in the stack.

Uploaded by

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

class Node {

String title;

double price;

String edition;

int pages;

Node next;

public Node(String title, double price, String edition, int pages) {

[Link] = title;

[Link] = price;

[Link] = edition;

[Link] = pages;

[Link] = null;

class Stack {

Node top;

public Stack() {

[Link] = null;

public void push(Node book) {

if (top == null) {

top = book;

} else {

[Link] = top;

top = book;
}

public Node pop() {

if (top == null) {

return null;

} else {

Node poppedBook = top;

top = [Link];

[Link] = null;

return poppedBook;

public Node peek() {

return top;

public class Main {

public static void main(String[] args) {

Stack stack = new Stack();

// Push 5 books into the stack

[Link](new Node("Book 1", 10.0, "First Edition", 100));

[Link](new Node("Book 2", 15.0, "Second Edition", 200));

[Link](new Node("Book 3", 20.0, "Third Edition", 150));

[Link](new Node("Book 4", 12.0, "Fourth Edition", 180));

[Link](new Node("Book 5", 18.0, "Fifth Edition", 250));


// Find the top element of the stack

Node topBook = [Link]();

if (topBook != null) {

[Link]("The top book in the stack is: " + [Link]);

} else {

[Link]("The stack is empty.");

// Pop 2 books from the stack

Node poppedBook1 = [Link]();

Node poppedBook2 = [Link]();

// Display the remaining books in the stack

Node currentBook = [Link]();

[Link]("The remaining books in the stack are:");

while (currentBook != null) {

[Link]([Link]);

currentBook = [Link];

You might also like