Need a project done?

C++ Programming Developer

Search This Blog

Delete node linked list C++

Delete node linked list C++
Solution:
When we delete any node in linked list we've 2 cases:
Case 1: Delete First node
Case 2: Delete any node except first

#include <iostream>
using namespace std;

struct node{
int id;
node *next;
};

void print (node *h);
void delete_node(node *head,node *tail,int id);

int main(){
node *head = 0, *tail = 0;

while (1){
int n;
cout << "1. New Entry." << endl;
cout << "2. Print all." << endl;
cout << "3. delete_node item." << endl;
cin >> n;
if ( n == 1){
node *newPtr = new node;
newPtr -> next = NULL;

if (head == NULL){
head = newPtr;
tail = newPtr;
}
else{
tail ->next = newPtr;
tail = newPtr;
}

cout << "ID: ";
cin >> newPtr->id;
}
else if(n==2){
print(head);
}
else if (n==3){
cout << "ID to be deleted: "; int id; cin >> id;

//Case 1:
if (head -> id == id){
node *p = head;
head = head ->next;
delete p;
}
//Case 2:
else{
delete_node(head,tail,id);
}
}
else{
cout << "BY"<< endl;
break;
}
}
return 0;
}

void print (node *h){
while (h!=NULL){
cout << "ID: ";
cout << h->id << endl << endl;
h = h->next;
}
}

void delete_node(node *head,node *tail, int id){
//First we'll find the id in the linked list to be deleted.
node *forwardPtr = head;
node *backPtr = head;

while (forwardPtr != NULL){
if (forwardPtr->id == id){
break;
}
else if (forwardPtr == backPtr){
forwardPtr = forwardPtr->next;
}
else{//both pointers move side by side.
backPtr = backPtr->next;
forwardPtr = backPtr->next;
}
}
//at the end of loop we'll have the forward pointer pointing the node to be deleted and backPtr will be 1 step behind forwardPtr. i.e. just before forwardPtr.
if (forwardPtr == NULL){
cout << "ID not found" << endl;
return;
}
else{//if id found.
backPtr -> next = backPtr -> next -> next;
delete forwardPtr;
}
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."