Skip to content

Instantly share code, notes, and snippets.

@wieczorek1990
Last active May 5, 2016
Embed
What would you like to do?
Linked List in Java
class Book {
private int mPages;
public Book(int pages) {
mPages = pages;
}
public String toString() {
return String.format("This book has %d pages.", mPages);
}
}
class BookNode {
private Book mBook;
private BookNode mNext;
public BookNode(Book book) {
mBook = book;
}
public void setNext(BookNode next) {
mNext = next;
}
public BookNode getNext() {
return mNext;
}
public Book getBook() {
return mBook;
}
}
class BookList {
private BookNode mFirst;
private BookNode mLast;
public BookNode getFirst() {
return mFirst;
}
public void append(BookNode node) {
if (mFirst == null) {
mFirst = node;
mLast = node;
} else {
mLast.setNext(node);
mLast = node;
}
}
}
public class Main {
public static void main(String[] args) {
Book[] books = {
new Book(0),
new Book(1),
new Book(2)
};
System.out.println("Array:");
for (Book book: books) {
System.out.println(book);
}
BookList bookList = new BookList();
for (Book book: books) {
bookList.append(new BookNode(book));
}
System.out.println("\nList:");
BookNode node = bookList.getFirst();
while (node != null) {
System.out.println(node.getBook());
node = node.getNext();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment