|
Linked Lists
− What you should know for first test
Here are some less obvious things you should understand prior to the first test. The more obvious things we have covered in class with practice quesitons and programming exercises.
You should know what will happen (for better or worse) when you run the following code snippets
1) Why does the code below not do what the writer intended?
LinkedList<Integer> q = new LinkedList<Integer>();
for(int i=0;i < 10;i++){
q.add(i);
}
Iterator<Integer> it = q.iterator();
while(it.hasNext()){
Integer instance = it.next();
System.out.println(instance);
if(instance.equals(new Integer(2))){
it.remove();
System.out.println("removing");
}
}
System.out.println("size : " + q.size());
while(it.hasNext())
System.out.println(it.next() );
Some Possibley Suprising Examples of Parameterized Types
| |
Valid LinkedList<Comparable> f = new LinkedList<Comparable>();
Comparable[] comparableArray = new String[8];
|
Not acceptable
ArrayList<Comparable> f2 = new ArrayList<String>(); |
- Exercise 3: Add a method size() to our linkedList class that computes the number of elements in the list, by following links and count theelements unti the end of the lis is reached.
- Exercise 4:
The Linked list class in the standard library has an add method that allows efficient insertion at the end of the list. Implement this method (addLast()) for our
pared down version of LinkedList class. Add an instance field to the linked list class that points to the last node in the list. Make sure that the other mutator methods update that field.
- Exercise 5: Repeat the prior exercise but use a different implementation strategy. Remove the reference to the first node in the LinkedList class and make the next reference of the last node point to the first node, so that ll nodes forma cycyle. This is known as a circular linked list.
- Exercise 6: Write method firstMin() that determines the value of the
smallest item of type comparable in its list parameter and returns a pointer to the first node in the list that contains
that value. (If the list is empty, firstMin returns null.) Remember that it's ok to declare a LinkedList as follows:
LinkedList<Comparable> listOfComprables = new LinkedList<Comparable>();
Note however, the following is illegal
LinkedList<Comparable> f = new LinkedList<String>();
For example, if L and p are ListNode references:
- Exercise 7: Design and implement an insertion sort that operates on a linked list of nodes that each contain an integer.
- Exercise 8: Design and implement a Selection sort that operates on a linked list of nodes that each contain an integer.
- Exercise 9: Create a class called Palindrome. This class should have a method isPalindrome() that uses two linear linked lists to determine whether or not a String is a palindrome. Below is a reminder on how to use a JOptionPane. Make sure you import javax.swing.JOptionPane.
String word= JOptionPane.showInputDialog("Type in a potential palindrome");
Linked listcode
Top
|