OneCompiler

LinkedList.cpp

125

#include <iostream>
using namespace std;

class node{
public:
int val;
node* next;

node(int val){
  this->val = val;
  this->next = nullptr;
}

};

class ll{
private:
node* head;
public:
ll(){
head = nullptr;
}

void insert(int val){
  node* cur = new node(val);
  cur->next = head;
  head = cur;
}

void display(){
  node* temp = head;
  while(temp){
    cout<<temp->val<<" ";
    temp = temp->next;
  }
  cout<<"nullptr";
}

void deletenode(int val){
  node* cur = head;
  node* prev = nullptr;
  
  while(cur and cur->val!=val){
    prev = cur;
    cur=cur->next;
  }
  
  if(!cur){
    return;
  }
  if(!prev){
    cur->next = nullptr;
  }
  else{
    prev->next = cur->next;
    cur->next = nullptr;
  }
  delete cur;
}

};

int main()
{
// cout << "Hello, World!";
ll n;
n.insert(1);
n.insert(8);
n.insert(3);
n.insert(7);
n.display();
n.deletenode(3);
n.display();
return 0;
}