public class LinkedList<T extends Comparable<T>> { private class Node { private
ID: 3700147 • Letter: P
Question
public class LinkedList<T extends Comparable<T>> {
private class Node {
private T data;
private Node next, thread;
private Node(T data) {
this.data = data;
next = thread = null;
}
}
private Node head, tail;
public LinkedList() {
head = tail = null;
}
public void setThread(boolean pointToPrev) { /* YOU MUST IMPLEMENT */ }
Provide a RECURSIVE implementation for the setThread method. For this problem:
If pointToPrev is true, the method initializes the thread node reference of each node to the node that precedes it in the list. If the node is the first one, thread will be set to null. After the thread reference has been set, we will have a doubly-linked list.
If pointToPrev is false, the method initializes the thread node reference of every node (except the first one) to point to the first node in the list. The thread reference of the first node will be set to null.
No processing will take place if the list is empty.
Notice that thread has nothing to do with Java threads.
You will lose significant credit if you use any iteration statement (while, do while, for). Your solution must be recursive.
Notice the list is not a sorted list.
Driver
LinkedList<String> list = new LinkedList<String>();
list.add("F").add("A").add("M").add("C").add("M").add("W");
System.out.println("list: " + list);
list.setThread(true);
System.out.print("After threading: ");
/* prints list starting at last element, following thread */
list.printListThread();
Output:
list: W M C M A F
After threading: F A M C M W
Explanation / Answer
Node temp1, temp2;
temp2=temp1=head;
head->thread = NULL;
public void setThread(boolean pointToPrev)
{
if(list == NULL) / * OR if (temp1==NULL) */
return;
if(pointToPrev)
{
temp1 = temp1->next;
temp1->thread = temp2;
temp2=temp2->next;
if(temp1->next!=NULL)
{
setThread(true);
}
else
return;
}
if(!pointToPrev)
{
temp1=temp1->next;
temp1->thread = head;
if(temp1->next!=NULL)
{
setThread(false);
}
else
return;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.