C++ Question: Consider a linked list made of nodes of the following struct: stru
ID: 3571486 • Letter: C
Question
C++ Question:
Consider a linked list made of nodes of the following struct:
struct ListNode
{
double data;
ListNode* next;
}
Assume that each ListNode in a linked list has an index equal to its distance (in number of links) from the head node. For example, for a linked list of length 4, the head node will have index 0, the second node will have index 1, the third node will have index 2, and the tail node will have index 3. Note the similarity with the way that arrays are indexed.
Write a function with the following prototype:
ListNode* swapWithHead(ListNode* head, int index);
The function should accept a pointer to the head of a list as well as an index. It should locate the node at the given index and swap it with the head node. The function should return a pointer to the new head if the swap is possible and a pointer to the original head if the swap is not possible.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
struct ListNode
{
double data;
ListNode* next;
int index;
}
ListNode* swapWithHead(ListNode* head, int index){
if(head == NULL || head->next == NULL)
return head;
ListNode* temp = head;
while(temp->next != NULL){
if(temp->next->index == index){
ListNode* newHead = temp->next;
ListNode* nextToHead = head->next;
temp->next = head;
head->next = temp->next->next;
newHead->next = nextToHead;
head = newHead;
return head;
}
temp = temp->next;
}
return head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.