Java Reference
In-Depth Information
if (w1.equals(w2)) System.out.printf("is a palindrome\n");
else System.out.printf("is not a palindrome\n");
System.out.printf("Type a phrase. (To stop, press 'Enter' only): ");
aPhrase = getPhrase(in);
}
} //end main
public static LinkedList getPhrase(Scanner in) {
LinkedList phrase = new LinkedList();
String str = in.nextLine();
for (int h = str.length() - 1; h >= 0; h--)
phrase.addHead(new NodeData(str.charAt(h)));
return phrase;
}
public static LinkedList lettersLower(LinkedList phrase) {
LinkedList word = new LinkedList();
while (!phrase.empty()) {
char ch = phrase.getHeadData().getData();
if (Character.isLetter(ch)) word.addTail(new NodeData(Character.toLowerCase(ch)));
phrase.deleteHead();
}
return word;
}
} //end class P3_5Palindrome
the solution presented was used mainly to show how linked lists can be manipulated. the problem can be
solved more efficiently using character arrays or strings where we would have direct access to any character of the
given phrase. For instance, we would be able to compare the first and last letters directly. even in the solution presented
here, we could clean up the phrase as it is being input by retaining letters only and converting them to lowercase. as an
exercise, write a program to solve the problem using arrays.
Note
3.12 Saving a Linked List
When we create a linked list, the actual “pointer” value in a node is determined at run time depending on where, in
memory, storage for the node is allocated. Each time the program is run, the pointer values will change. So, what do
we do if, having created a linked list, we need to save it for later use?
Since it would be useless to save the pointer values, we must save the contents of the nodes in such a way that we
would be able to re-create the list when needed. The simplest way to do this is to write the items to a file (see Chapter 8)
in the order that they appear in the linked list. Later, we can read the file and re-create the list as each item is read.
Sometimes, we may want to compact a linked list into an array. One reason might be that the linked list is sorted
and we want to search it quickly. Since we are restricted to a sequential search on a linked list, we can transfer the
items to an array where we can use a binary search.
 
 
Search WWH ::




Custom Search