reverse a linked list? [duplicate]

旧城冷巷雨未停 提交于 2019-11-29 08:59:05

Well, the first thing I notice is that you are doing

temp = new node

and then, on every interaction:

temp = temp->next

but you are never assigning temp->next

so when you finally override the list pointer you are surely giving back some funny value.

You do this:

while (true){
    if (current == NULL){
        temp = NULL;
        break;
    }
    temp->number = current->number;
    current = current->next;
    temp = temp->next;
}

Suppose it works as you intended. When the while exists, temp will be NULL, right ?

listpointer = temp; <=> listpointer = NULL;

So this might be a problem.

Without checking your code I ask you this, are you sure that your linkedlist is working?

void reverse(Node** list) {
    Node* previous=NULL;
    Node* current=*list;
    while (NULL!=current) {
        std::swap(previous, current->next);
        std::swap(previous, current);
    }
    *list=previous;
}

why not :

  1. measure the length of your list

  2. fill the append your list with zeros until you reach double the size of your existing list

  3. go to the beginning of the list,

  4. read contents one by one until you reach the end of the original list

  5. while moving on the original list:

  6. copy the contents of current node into the node having pointer advancing by

    ((original list length - current node index) * 2 + 1 ) * size of node

  7. after you are done, get the pointer of the first node after your original list to point at a reversed list

without having to create a new list or to work on multiple iterations or to modify the existing data structure (not converting it into a double linked list)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!