Reversing a Single Linked List

Neeraj Sharma

Neeraj Sharma

@neeraj-iAaNcG Oct 22, 2024
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?

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • KenJackson

    KenJackson

    @kenjackson-mBf7HF Jun 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;
    }