entry link element 張三 李四 王五 Draw sketch to show an entry and

advertisement
1. Draw sketch to show an entry and an element, respectively, in a linked
list. element link
張三
李四
王五
entry
2.Draw sketch to show a list containing elements A, B, and C that is stored
in singly-linked list and in doubly-linked list, respectively.
1.single-linked list
B
A
C
null
2.double-linked list
A
B
C
null
3. Write Java code to declare class Entry<E> for Problem No. 2 above.
1.single-linked list
public class Entry<E> {
E element;
Entry<E> next;
public Entry(){
element=null;
next=null;
}
}
2.double-linked list
public class Entry<E> {
E element;
Entry<E> next;
Entry<E> previous;
public Entry(){
element=null;
next=null;
previous=null;
}
}
4.Comparing the usage of ArrayList and LinkedList, under what
circumstances would you use each one of them?
Ans: If you iterate through a list and make insertions and/or removals
during the iteration, use LinkedList. If you access and/or replace elements
at widely varying indexes, use ArrayList.
5.In the Java Collection Framework, the LinkedList class is designed as a
circular, doubly-linked list with a dummy entry (pointed to by the header
field). What is the main advantage of this approach over a circular,
doubly-linked list with head and tail fields?
Ans:In the LinkedList class, the main advantage of having a dummy entry is that
every entry, even the first or last entry, has a predecessor and a successor, so there
is no need for a special case to insert or delete at the front or back of a LinkedList
object.
6. Hypothesize the output from the following method segment:
LinkedList<Character> letters = new LinkedList<Character>();
ListIterator<Character> itr = letters.listIterator();
itr.add ('f');
itr.add ('t');
itr.previous();
itr.previous();
itr.add ('e');
itr.add ('r');
itr.next();
itr.add ('e');
itr.add ('c');
itr = letters.listIterator();
itr.add ('p');
System.out.println (letters);
Test your hypothesis with a project that includes the above code in a main method.
The output is
[p, e, r, f, e, c, t]
7. Rewrite the insert method in the Editor class to insert the given line after the current
line. For example, if the text is
>I was
older then
and the command is
$Insert
so much
then the text becomes
I was
>so much
older then
The newly added line becomes the current line.
Ans:
/**
* Inserts a specified line after the current line. The inserted line
* becomes the current line.
*
* @param s – the line to be inserted.
*
* @throws RunTimeException – if s has more than
*
*
MAX_LINE_LENGTH
characters.
*/
protected void insert (String s)
{
if (s.length() > MAX_LINE_LENGTH)
throw new RuntimeException (LINE_TOO_LONG
+MAX_LINE_LENGTH);
if (current.hasNext())
current.next();
current.add (s);
current.previous();
} // method insert
Download