Data Structures Problem solving questions on Linked Lists Question 1: reverse a
ID: 3835993 • Letter: D
Question
Data Structures Problem solving questions on Linked ListsQuestion 1: reverse a singly-linked list both iteratively and recursively.
Question 2: given a singly-linked list, write a function that returns the middle element of the list by using a single pass. This means that you may not first iterate through the list and get its length. Data Structures Problem solving questions on Linked Lists
Question 1: reverse a singly-linked list both iteratively and recursively.
Question 2: given a singly-linked list, write a function that returns the middle element of the list by using a single pass. This means that you may not first iterate through the list and get its length. Problem solving questions on Linked Lists
Question 1: reverse a singly-linked list both iteratively and recursively.
Question 2: given a singly-linked list, write a function that returns the middle element of the list by using a single pass. This means that you may not first iterate through the list and get its length.
Explanation / Answer
Question 1:
Algorithm: Iterative
The code before your while loop looks like the code inside the while loop. This sort of suggests you can replace it with a do-while loop. Thus your iterative code should look more like this:
Recursive
Converting a loop into recursion requires an extra function to cope with the extra variable used for last. So the main recursion looks like this (it just calls the actually recursive function setting up the last parameter). You should have this wrapper function to help users of the code from calling the recursive part of the function incorrectly.
Now we can do the recursion. Again the edge case is still NULL.
Question 2:
/* Function to get the middle of the linked list*/
void printMiddle(struct node *head)
{
struct node *slow_ptr = head;
struct node *fast_ptr = head;
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d] ", slow_ptr->data);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.