1. Complete the code for a function that replaces each occurrence of value x by
ID: 3552865 • Letter: 1
Question
1. Complete the code for a function that replaces each occurrence of value x by value y in a linked list with first node pointer p.
Assume the info type is int. :
void replaceLinkedList(Node* p, int x, int y)
2. Complete the code for a function that inserts a node with info value x before, and a node with info value z after, each node with info value y in a linked list with first node pointer p.
Assume the info type is int and that x,y and z contain distinct. The function returns a pointer to the first node of the modified list. :
Node* InsertBeforeAndAfter(Node* p, int x, int y, int z)
Utility function:
Node * MakeNode(int newVal, Node* successor)
{
Node * tmp = malloc(sizeof(Node));
assert(tmp != NULL);
tmp->info = newVal; tmp->next = successor;
return tmp;
}
Explanation / Answer
1. void replaceLinkedList(Node* p, int x, int y)
{
while( p != NULL )
{
if( p->info == x )
p->info = y ;
p = p->next ;
}
}
2.
Node* InsertBeforeAndAfter(Node* p, int x, int y, int z)
{
Node* ret = p ;
Node* nxt ;
if(p->info ==y )
ret = MakeNode(x,p) ;
else{
while( p->info == y )
p = p->next ;
nxt = MakeNode(x,p) ;
}
if(p->next != NULL )
nxt = MakeNode(z,p->next) ;
else{
p->next=malloc(sizeof(Node));
nxt = MakeNode(z,p->next);
}
return ret;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.