surrealtrauma said:
if i have circular linked list like:
14->12->10->8->6->4->2->0->//
how can i revises it as
0->2->4->6->8->10->12->14->//
is there any other method besides swap?
Thank you
Probably, you are talking about the following idiom to reverse a single
linked list in place:
template < typename T >
class slist_node {
public:
T data;
slist_node * next;
};
template< typename T >
slist_node<T>* reverse_slist( slist_node<T> * & head ) {
slist_node<T> * prev = 0;
while ( head != 0 ) {
// want to cyclicly permute the values of the variables
// head -> prev -> head->next -> head.
// cycle realized via two transpositions:
std::swap( prev, head->next );
std::swap( head, prev );
}
return( prev );
}
Now, of course, you could realize the cyclic permutation directly:
template< typename T >
slist_node<T>* reverse_slist( slist_node<T> * & head ) {
slist_node<T> * prev = 0;
while ( head != 0 ) {
// want to cyclicly permute the values of the variables
// head -> prev -> head->next -> head.
// explicity cycle:
slist_node<T> * dummy = head->next;
head->next = prev;
prev = head;
head = dummy;
}
return( prev );
}
However, an optimizing compiler would likely produce identical code for
both solutions. I do not know of any more efficient way to reverse a list.
Best
Kai-Uwe Bux