I would be wondered if there exists some logic to reverse the linked list using only two pointers.
The following is used to reverse the single linked list using three pointers namely p, q, r:
struct node
{
int data;
struct node *link;
};
void reverse()
{
struct node *p = first,
*q = NULL,
*r;
while (p != NULL)
{
r = q;
q = p;
p = p->link;
q->link = r;
}
q = first;
}
Is there any other alternate to reverse the linked list? what would be the best logic to reverse a singly linked list, in terms of time complexity?
Yes there is a way using only two pointers. That is by creating new linked list where the first node is the first node of the given list and second node of the first list is added at the start of the new list and so on.
Using two pointers while maintaining time complexity of O(n), the fastest achievable, might only be possible through number casting of pointers and swapping their values. Here is an implementation:
Here is a slightly different, but simple approach in C++11:
Output here
To swap two variables without the use of a temporary variable,
fastest way is to write it in one line
Similarly,
using two swaps
solution using xor
solution in one line
The same logic is used to reverse a linked list.
here is a little simple solution...
I hate to be the bearer of bad news but I don't think your three-pointer solution actually works. When I used it in the following test harness, the list was reduced to one node, as per the following output:
You won't get better time complexity than your solution since it's O(n) and you have to visit every node to change the pointers, but you can do a solution with only two extra pointers quite easily, as shown in the following code:
This code outputs:
which I think is what you were after. It can actually do this since, once you've loaded up
first
into the pointer traversing the list, you can re-usefirst
at will.