You have not provided the code for SLL class. However assuming it has a nested Node class for single linked list with data and next variables inside it, the following code will work.
public static SLL<T> reverse()
{
SLL<T> rev = new SLL<T>();
Node n = head;
Node prev = null;
Node newHead = null;
while(n != null){
newHead = new Node(n.data);
newHead.next = prev;
prev = newHead;
n = n.next;
}
rev.head = newHead;
return rev;
}
The time complexity of above algorithm is O(n)
Get Answers For Free
Most questions answered within 1 hours.