简体   繁体   中英

Creating a second singly-linked list in reverse order of another list

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 eg '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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM