Last active
May 5, 2016 22:04
-
-
Save wieczorek1990/32f149573f2e746dc34003a0372b04fa to your computer and use it in GitHub Desktop.
Linked List in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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