Creating a second inverted singly-linked list based on another list

Refresh

February 2019

Views

5 time

0

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

It doesn't sound hard at all but 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. Thanks in advance.

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

0 answers