Skip to content

Instantly share code, notes, and snippets.

@wieczorek1990
Last active May 5, 2016 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wieczorek1990/32f149573f2e746dc34003a0372b04fa to your computer and use it in GitHub Desktop.
Save wieczorek1990/32f149573f2e746dc34003a0372b04fa to your computer and use it in GitHub Desktop.
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