How many pointers are required to reverse a link list?
Answers were Sorted based on User's Feedback
Answer / prits
Using 3 pointers:
curr, next, result pointers, curr points to current node,
next obviously points to the next node, result points to
the new reversed linked list
void reverse_single_linked_list(struct node** headRef)
{
struct node* result = NULL;
struct node* current = *headRef;
struct node* next;
while (current != NULL)
{
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
}
*headRef = result;
}
Is This Answer Correct ? | 14 Yes | 1 No |
Answer / patrick
You cannot must have a pointer to a pointer if you want to
modify the pointer.
void reverse(node** head)
{
node* cur = *head;
*head = null;
while (cur)
{
node* next = cur->next;
cur->next = *head;
*head = cur;
cur = next;
}
}
Besides the head pointer, you will need two local pointers.
Is This Answer Correct ? | 4 Yes | 1 No |
Answer / vivek
using 2 pointer:
void reverse(node* head_in_out)
{
if(head_in_out)
{
node* aCurr = head_in_out;
node* aNext = NULL;
while (aCurr)
{
head_in_out = aCurr->next;
aCurr->next = aNext;
aNext = aCurr;
aCurr = head_in_out;
}
}
}
Is This Answer Correct ? | 1 Yes | 2 No |
Answer / vivek
# 3 using 2 pointer:
void reverse(node* head_in_out)
{
if(head_in_out)
{
node* aCurr = head_in_out;
node* aNext = NULL;
while (aCurr)
{
head_in_out = aCurr->next;
aCurr->next = aNext;
aNext = aCurr;
aCurr = head_in_out;
}
head_in_out = aNext; // Bug in above 3rd answer.
}
}
Is This Answer Correct ? | 1 Yes | 2 No |
What is the use of 'this' pointer?
What is the purpose of templates in c++?
What is the best c++ book?
What is the difference between map and hashmap in c++?
How to detect memory leaks in c++
#include<iostream.h> void main() { class x { public: int func(int) { cout<<"cool"; return 1; } } }
What is binary object model?
What is an incomplete type in c++?
How do you instruct your compiler to print the contents of the intermediate file showing the effects of the preprocessor?
sir there is some problem with nokia5130c-2,when we are trying to upload movies from net then there is a error occurred"FORMAT NOT SUPPORTED" bt its all ready in 3gp format.please tell me what i do now?
Is overriding possible in c++?
Explain some examples of operator overloading?