Flip linked list?

I am trying to reorder the next linked list, I did this, but the inverted list does not seem to print. Where am I wrong?

//reverse the linked list #include <iostream> using namespace std; struct node{ int number; node *next; }; node *A; void addNode(node *&listpointer, int num){ node *temp; temp = new node; temp->number = num; temp->next = listpointer; listpointer = temp; } void reverseNode(node *&listpointer){ node *temp,*current; current = listpointer; temp = new node; while (true){ if (current == NULL){ temp = NULL; break; } temp->number = current->number; current = current->next; temp = temp->next; } listpointer = temp; } int main(){ A = NULL; addNode(A,1); addNode(A,2); addNode(A,3); while (true){ if (A == NULL){break;} cout<< A->number << endl; A = A->next; } cout<< "****" << endl; reverseNode(A); while (true){ if (A == NULL){break;} cout<< A->number << endl; A = A->next; } cout<< "****"<< endl; return 0; } 
0
source share
5 answers

Ok, the first thing I notice is what you do

temp = new node

and then with each interaction:

temp = temp-> next

but you never assign temp-> next

therefore, when you finally redefine the list pointer, you will surely return some kind of ridiculous value.

+3
source

You do it:

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

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

 listpointer = temp; <=> listpointer = NULL; 

So this can be a problem.

+1
source

Without checking my code, I ask you this, are you sure your linked list is working?

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

why not:

  • measure the length of your list

  • fill the list with zeros until you double the size of the existing list.

  • go to the top of the list,

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

  • when moving through the source list:

  • copy the contents of the current node to node by specifying a pointer

    ((the initial length of the list is the current index of the node) * 2 + 1) * the size of the node

  • after you finish, get the pointer of the first node after the original list points to the reverse list

without the need to create a new list or work with multiple iterations or modify an existing data structure (do not convert it to a double linked list)

-1
source

Source: https://habr.com/ru/post/1338565/


All Articles