CrazyEngineers
  • Reversing a Single Linked List

    Neeraj Sharma

    Member

    Updated: Oct 22, 2024
    Views: 1.0K
    I have a program for reversing a single linked list

    node *rev( node *head ) {
      node *next;
      node *curr = head;
      node *prev = NULL;
      while (curr != NULL) {
        next      = curr->next;
        curr->next = prev;
        prev      = curr;
        curr      = next;
        }
      return prev;
      }
    I have used 3 pointers here *next, *curr and *prev.
    Can somebody help me in performing this task using just 2 pointers?
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • KenJackson

    MemberJun 13, 2012

    I thought surely there must be a way. But I couldn't think of one.

    However, you can easily do it with only two declared pointer and use your argument as the third pointer. (I renamed "node" to "temp" to reduce confusion with the field name.)
    node *rev(node *head)
    {
        node *temp;
        node *prev = NULL;
        while (head != NULL)
        {
            temp = head->next;
            head->next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register