Question 4 Consider the SinglyLinkedList class partially given below. Instance v
ID: 672963 • Letter: Q
Question
Question 4
Consider the SinglyLinkedList class partially given below. Instance variable head
contains the address of the first node, and tail contains the address of the last node. Add to the
SinglyLinkedList } class a method public void reverse() which will reverse the order of the nodes by
reversing the links. For example after the reversing is completed the head will now refer to the node
that was originally the last node of the list.
public class SinglyLinkedList<E>
{
public class Node<E>
{
private E data;
private Node<E> next;
public Node ( ) {
data = null;
next = null;
}
public Node( E newData, Node<E> newNext ){
this.data = newData;
this.next = newNext;
}
} // end of Node class
private Node<E> head; // Reference to first node in the list
private Node<E> tail; //Reference to the last node in the list
public SinglyLinkedList( ){
head = tail = null;
}
//other methods
} // end of SinglyLinkedList class
Explanation / Answer
static void reverse(struct node** head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.