Answer to Question #273340 in C++ for Korea

Question #273340

Delete node

1
Expert's answer
2021-11-30T00:36:47-0500
#include <bits/stdc++.h>
using namespace std;


class Node{
    public:
    	int d;
    	Node* nxt;
    };
    void insert(Node** head_r, int new_d)
    {
    	Node* new_n = new Node();
    	new_n->d = new_d;
    	new_n->nxt = (*head_r);
    	(*head_r) = new_n;
    }
    void delete(Node** head_r, int k)
    {
    	Node* temp = *head_r;
    	Node* prev = NULL;
    	if (temp != NULL && temp->d == k)
    	{
    		*head_r = temp->nxt;
    		delete temp;	
    		return;
    	}
    	else
    	{
    	while (temp != NULL && temp->d != k)
    	{
    		prev = temp;
    		temp = temp->nxt;
    	}
    
    	if (temp == NULL)
    		return;
    	prev->nxt = temp->nxt;
    	delete temp;
    	}
    }
    
    void display(Node* n)
    {
    	while (n != NULL)
    	{
    		cout << n->d << " ";
    		n = n->nxt;
    	}
}


int main()
{
	Node* h = NULL;
	insert(&h, 10);
	insert(&h, 11);
	insert(&h, 12);
	puts("Before deletion: ");
	display(h);
	delete(&h, 12);
	puts("\nAfter deletion: ");
	display(h);
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS