Java Reference
In-Depth Information
MyAbstractList<E>
m
1
Node<E>
MyLinkedList<E>
element: E
next: Node<E>
-head: Node<E>
-tail: Node<E>
1
+MyLinkedList()
+MyLinkedList(elements: E[])
+addFirst(e: E): void
+addLast(e: E): void
+getFirst(): E
+getLast(): E
+removeFirst(): E
+removeLast(): E
Creates a default linked list.
Creates a linked list from an array of elements.
Adds an element to the head of the list.
Adds an element to the tail of the list.
Returns the first element in the list.
Returns the last element in the list.
Removes the first element from the list.
Removes the last element from the list.
Link
F IGURE 24.11
MyLinkedList implements a list using a linked list of nodes.
Assuming that the class has been implemented, Listing 24.5 gives a test program that uses
the class.
L ISTING 24.5
TestMyLinkedList.java
1 public class TestMyLinkedList {
2
/** Main method */
3
public static void main(String[] args) {
4
// Create a list for strings
5
MyLinkedList<String> list = new MyLinkedList<>();
create list
6
7 // Add elements to the list
8 list.add( "America" ); // Add it to the list
9 System.out.println( "(1) " + list);
10
11 list.add( 0 , "Canada" ); // Add it to the beginning of the list
12 System.out.println( "(2) " + list);
13
14 list.add( "Russia" ); // Add it to the end of the list
15 System.out.println( "(3) " + list);
16
17 list.addLast( "France" ); // Add it to the end of the list
18 System.out.println( "(4) " + list);
19
20 list.add( 2 , "Germany" ); // Add it to the list at index 2
21 System.out.println( "(5) " + list);
22
23 list.add( 5 , "Norway" ); // Add it to the list at index 5
24 System.out.println( "(6) " + list);
25
26 list.add( 0 , "Poland" ); // Same as list.addFirst("Poland")
27 System.out.println( "(7) " + list);
28
29 // Remove elements from the list
30 list.remove( 0 ); // Same as list.remove("Poland") in this case
31 System.out.println( "(8) " + list);
append element
print list
insert element
append element
append element
insert element
insert element
insert element
remove element
 
 
Search WWH ::




Custom Search