Akshit
Akshit

Reputation: 103

Reversing a List Iteratively-Logical Error

Here I am trying to reverse the list iteratively. But the problem is that how large is the list say 3->2->4->NULL, in the end it becomes 3->NULL i.e. the list with only one element. Please tell what is the problem in the code.

    struct node *reverselist(struct node *head)
{
     struct node *list=head;
     if(head==NULL)
     {
           printf("\nThe list is empty\n");
           return head;
     }
     if(head->next==NULL)
     {
           printf("\nThe list has only one element\n");
           return head;
     }
     struct node *cur=head;
     struct node *new=head->next;
     while(cur->next!=NULL)
     {
           cur->next=new->next;
           new->next=cur;
           new=cur->next;
         }
     return list;
}

Upvotes: 1

Views: 73

Answers (2)

Navnath Godse
Navnath Godse

Reputation: 2225

Your logic is wrong - Pointer new is updating correctly but cur is fixed.

Instead of try this

struct node *reverselist(struct node *head)
{
    struct node *temp;
    struct node *newHead = NULL;
    struct node *curNode = head;

    while(curNode != NULL) {
        temp = curNode->next;
        curNode->next = newHead;
        newHead = curNode;
        curNode = temp;
    }

    return newHead;
}

Upvotes: 1

Peter Miehle
Peter Miehle

Reputation: 6070

you iterate over cur->next and change cur->next. So first: you never change head and second you move the last element to the front after head.

Upvotes: 0

Related Questions