I am a beginner and was trying to reverse a linked list so here i wrote a function to reverse a linked list.
void reverse_list(struct node **head_ref)
{
struct node *temp = *head_ref;
if(temp == NULL)
return;
else if(temp->next == NULL)
return;
else
{
struct node *temp_r = temp;
int count = count_list(temp); // no.of nodes in the list
while(temp != NULL)
{
struct node *temp_t = temp_r;
int i;
for(i=0;i<count;i++)
{
if(i!=0)
temp_t = temp_t->next; // loop to find the node which is to be swapped with temp
}
if(temp_t == temp) // base condition to stop swapping
return;
else
{
swap_node(&temp_r,temp->data,temp_t->data);
}
temp = temp->next; // traverse through the list
count--;
}
}
}
logic i used: i want to reverse the linked list by swapping the node in this way (1,n) ,(2,n-1),(3,n-3) ..
but when i execute this code it only prints the first element of the list.
After running debugger i understood that i made two copies of the original list and i was actually swapping the nodes of two different list which is not possible by the function swap_node()
defined in the code, here is the swap_node()
function
void swap_node(struct node **head_ref,int key1,int key2) // function to swap two nodes.
{
if(key1==key2)
return;
// search for key1
struct node *prevx = NULL, *currx = *head_ref;
while(currx && currx->data != key1)
{
prevx = currx;
currx = currx->next;
}
//search for key2
struct node *prevy = NULL, *curry = *head_ref;
while(curry && curry->data!=key2)
{
prevy = curry;
curry = curry->next;
}
// if key1 or key2 are not present in the list
if(currx == NULL || curry == NULL)
return;
// check if key1 is not head of the list
if(prevx != NULL)
prevx->next = curry;
else
*head_ref = curry; // then make key2 the head
// check if key2 is not head of the list
if(prevy != NULL)
prevy->next = currx;
else
*head_ref = currx; // then make key2 the head
// swapping the next pointers of the nodes
struct node *temp = curry->next;
curry->next = currx->next;
currx->next = temp;
}
i want to reverse the linked list using the above logic but i am unable to do that , so please someone help me out to achieve this, how can i improve this code and how to proceed .
thanxs in advance.