0

I need to create a function that takes a normal singly-linked list and creates another list in reverse order of the first list, the first element in the new list will be the last element in the original list and so on.

My function for some reason only ever returns the same number over and over for the entirety of the new list. Therefore, if the last number in my original list is e.g. '50', the new list will be made up entirely of '50's.

This is my code, what am I doing wrong? If anyone wants me to post the whole program for more clarity or context give me a shout.

void invert() {
    node *list1=top,*newlist,*temp,*prev;
    while (list1->next!=NULL) {
        list1=list1->next;
    }
    newlist=new node;
    newlist->num=list1->num;
    newlist->next=NULL;
    if (top2==NULL) {
        top2=newlist;
    }
    else {
        for (temp=top2;temp!=NULL;temp=temp->next) {
            prev=temp;
        }
        prev->next=newlist;
    }
    list1->next=NULL;
}
2
  • It's good time to learn how to debug small programs: ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Feb 12, 2019 at 2:04
  • Iterate forward through the from list. For each node, copy it and insert the copy at the head of the to list. Commented Feb 12, 2019 at 2:29

1 Answer 1

2

Your code cannot be correct as it creates only a single new node and then modifies the next link in existing nodes. From your requirements, you have to create a new list which means cloning all nodes and linking them in the reverse order.

Following the suggestion of @user4581301, I came up with the following:

node* invert(node* list)
{
    node* inverted = NULL;
    // run through original in order
    for (node* p = list; p != NULL; p = p->next) 
    {
        // clone the node
        node* newNode = new node(); 
        newNode->num = p->num;
        // and link it so that the predecessor in the original list
        // (which has been processed in the previous iteration) is
        // linked as next node
        newNode->next = inverted;
        inverted = newNode;
    }
    return inverted;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.