LINKED LIST DATA STRUCTURE
CREATE a user-defined Class LinkedList to store a list of Books.
Class Linked List contains it’s own constructors to instantiate its private data.
Define mutator and accessor methods.
Define method add and remove for the linked list.
Then defined an application class to manipulate the list of books.
public class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class LinkedList {
private Node head;
private Node tail;
public LinkedList() {
head = null;
tail = null;
}
public void add(Book book) {
Node node = new Node(book);
if (tail == null) {
head = node;
} else {
tail.next = node;
}
tail = node;
}
public void remove(Book book) {
if (head != null) {
if (head.next == null
&& (head.book.getTitle().equals(book.getTitle()) || tail.book.getTitle().equals(book.getTitle()))) {
head = null;
tail = null;
} else if (head.book.getTitle().equals(book.getTitle())) {
head = head.next;
} else {
for (Node cur = head; cur.next != null; cur = cur.next) {
if (cur.next.book.getTitle().equals(book.getTitle())) {
if (cur.next.next == null) {
tail = cur;
}
cur.next = cur.next.next;
break;
}
}
}
}
}
public Book getBook(int index) {
for (Node cur = head; cur != null; cur = cur.next) {
if (index == 0) {
return cur.book;
}
index--;
}
return null;
}
private static class Node {
Book book;
Node next;
Node(Book book) {
this.book = book;
next = null;
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("1. Add book\n2. Remove book\n3. Get book\n0. Exit");
switch (in.nextLine()) {
case "1":
System.out.print("Title: ");
linkedList.add(new Book(in.nextLine()));
break;
case "2":
System.out.print("Title: ");
linkedList.remove(new Book(in.nextLine()));
break;
case "3":
System.out.print("Index: ");
Book book = linkedList.getBook(Integer.parseInt(in.nextLine()));
System.out.println(book == null ? "Not found" : book.getTitle());
break;
case "0":
System.exit(0);
}
}
}
}
Comments
Leave a comment