Java Reference
In-Depth Information
32
33 list.remove( 2 ); // Remove the element at index 2
34 System.out.println( "(9) " + list);
35
36 list.remove(list.size() - 1 ); // Remove the last element
37 System.out.print( "(10) " + list + "\n(11) " );
38
39 for (String s: list)
40 System.out.print(s.toUpperCase() + " " );
41 }
42 }
remove element
remove element
traverse using iterator
(1) [America]
(2) [Canada, America]
(3) [Canada, America, Russia]
(4) [Canada, America, Russia, France]
(5) [Canada, America, Germany, Russia, France]
(6) [Canada, America, Germany, Russia, France, Norway]
(7) [Poland, Canada, America, Germany, Russia, France, Norway]
(8) [Canada, America, Germany, Russia, France, Norway]
(9) [Canada, America, Russia, France, Norway]
(10) [Canada, America, Russia, France]
(11) CANADA AMERICA RUSSIA FRANCE
24.4.3 Implementing MyLinkedList
Now let us turn our attention to implementing the MyLinkedList class. We will discuss
how to implement the methods addFirst , addLast , add(index, e) , removeFirst ,
removeLast , and remove(index) and leave the other methods in the MyLinkedList class
as exercises.
24.4.3.1 Implementing addFirst(e)
The addFirst(e) method creates a new node for holding element e . The new node becomes
the first node in the list. It can be implemented as follows:
1 public void addFirst(E e) {
2
Node<E> newNode = new Node<>(e); // Create a new node
create a node
link with head
head to new node
increase size
3
newNode.next = head; // link the new node with the head
4
head = newNode; // head points to the new node
5
size++; // Increase list size
6
7 if (tail == null ) // The new node is the only node in list
8 tail = head;
9 }
was empty?
The addFirst(e) method creates a new node to store the element (line 2) and inserts the
node at the beginning of the list (line 3), as shown in FigureĀ 24.12a. After the insertion, head
should point to this new element node (line 4), as shown in FigureĀ 24.12b.
 
 
Search WWH ::




Custom Search