I have written a code to reverse a linked list , i have done insert , display and delete now I am writing to reverse the linked list!!!
I know there two ways to do this.
1) make the head pointer point to NULL and then point the consecutive nodes point to the previous ones, and at the end make the tail node as head.
2) Swap first with last , second with second last likewise
I am applying the first method below is my code.In this if list NULL or there's only one node then it's printing the respective couts' but while list is there it's printing till cout <<"here" <<endl; , why so?
I tried the second also but in this console is disappearing as I am trying to reverse though same like above the empty list and the single list is getting printed.. please help!!!
At any given time you have three consecutive nodes to look at: previous, current, and next.
You should update the current. It does point to the next, but in reverse it will point to the previous. You have to store the current->next to next before changing it. After the update you have to move forward by advancing the previous and current. The order of pointer assignments is the key.
At start the previous is a nullptr, so the head->next becomes nullptr, as is proper for the last node of the list.
At the end you have a pointer to the last node of the original list, i.e. the first node of the reversed list. Make head point to it.
Thanks for the reply . but I am new to this and not aware of the term nullptr . Is it a node whose content is NULL or is it simply NULL ? I tried to google but did not get any answer.