Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linked list reverse without temp

Is there any way to reverse linked list without using temp variable in C? Thanks in advance.

the famous approach:

Element *reverse(Element *head)
{
    Element *previous = NULL;

    while (head != NULL) {
        // Keep next node since we trash
        // the next pointer.
        Element *next = head->next;

        // Switch the next pointer
        // to point backwards.
        head->next = previous;

        // Move both pointers forward.
        previous = head;
        head = next;
    }

    return previous;
}

uses temp variable

Saurabh

like image 979
Saurabh Ghorpade Avatar asked Jan 11 '12 22:01

Saurabh Ghorpade


People also ask

How can we reverse an array without TEMP variable?

If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable.

How do you reverse a linked list efficiently?

The recursive approach to reverse a linked list is simple, just we have to divide the linked lists in two parts and i.e first node and the rest of the linked list, and then call the recursion for the other part by maintaining the connection.

How do you reverse a linked list without using a loop?

It is possible to reverse a double-linked list in O(1) by swapping it's head and tail pointers, and (depending on the implementation) setting some kind of a flag that will tell that the list should be now iterated backwards (i.e. following the back pointers to iterate forward, and following the next pointers to iterate ...


1 Answers

Note that your temp usage is actually generating two swap() calls, and can be replaced with:

swap(head->next,previous);
swap(previous,head);

You can swap without temps using xor, it is called xor swap.

like image 62
amit Avatar answered Oct 18 '22 05:10

amit