Data Structure Linked list Question:
Download Job Interview Questions and Answers PDF
Explain the most efficient method to reverse a linked list?
Answer:
To call the function:
newHead = reverse(head);
struct Node *reverse(Node *curp)
{
static struct Node *head = curp;
static struct Node *revHead = NULL;
if (curp == NULL)
return NULL;
if (curp->next == NULL)
revHead = curp;
else
reverse(curp->next)->next = curp;
if (curp == head) {
curp->next = NULL;
return revHead;
}
else
return curp;
}
newHead = reverse(head);
struct Node *reverse(Node *curp)
{
static struct Node *head = curp;
static struct Node *revHead = NULL;
if (curp == NULL)
return NULL;
if (curp->next == NULL)
revHead = curp;
else
reverse(curp->next)->next = curp;
if (curp == head) {
curp->next = NULL;
return revHead;
}
else
return curp;
}
Download Linked list Interview Questions And Answers
PDF
Previous Question | Next Question |
Do you know how to reverse String in Java? | Explain the steps to insert data into a singly linked list? |