In C++ Given the following struct and function prototypes: struct Node{ int data
ID: 3574106 • Letter: I
Question
In C++
Given the following struct and function prototypes:
struct Node{
int data;
Node *next;
};
typedef Node* NodePtr;
// Return pointer to Node with the same ‘data’ from a simple linked list;
// return NULL if not found.
NodePtr searchNode(NodePtr Head, int data);
// Print out the data from the linked list, starting from the Head node
void DisplayList(NodePtr Head);
a) We have a simple linked list with 6 nodes of data { 3,5,7,54,7 }. What is the output
of the following ?
NodePtr temp, cur, prev;
temp = searchNode(Head, 7);
if (temp!=NULL) {
cur=temp->next;
temp->next=NULL;
while(cur!=NULL) {
prev=cur;
cur=cur->next;
delete prev;
}
}
DisplayList(Head);
The following function is supposed to insert a node to the head of a linked list.
There is an error in it and please specify and correct the problem.
1 void addHead(NodePtr Head, int newdata){
2
3 NodePtr newPtr = new Node;
4
5 newPtr->data = newdata;
6 newPtr->next = Head;
7
8 Head = Head->next;
9 Head = newPtr;
10 delete newPtr;
11 }
Explanation / Answer
We have a simple linked list with 6 nodes of data { 3,5,7,54,7 }. What is the output
of the following ?
NodePtr temp, cur, prev;
temp = searchNode(Head, 7);
if (temp!=NULL) {
cur=temp->next;
temp->next=NULL;
while(cur!=NULL) {
prev=cur;
cur=cur->next;
delete prev;
}
}
DisplayList(Head);
basically this code is finding the first position of 7 and delete all the nodes next to it and printing them
hence it prints 3 5 7
b)
void addHead(NodePtr Head, int newdata){
NodePtr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = Head;
Head = Head->next;
Head = newPtr;
delete newPtr;
}
line Head = newPtr; say head is pointing to newPtr means both of them are refering to same node newPtr
so if we delete newPtr head referes to null
so correct code is
void addHead(NodePtr Head, int newdata){
NodePtr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = Head;
Head = newPtr;
}