Hello people, I need some help regarding the insertion/deletion of data in the middle node. My problem is, if you insert a node on the middle, the existing middle node gets replaced (the nodes between the inserted node in the middle should only move left and right). And when I delete the middle node, it would only change the value to 0. I hope you can help me with this, thanks :D
#include<conio.h>
#include<iostream>
#include<windows.h>
using namespace std;
class node
{
private:
int i;
node *next;
node *head;
public:
node();
~node();
void addFirst(int x);
void display();
void deleteFirst();
void addEnd(int x);
void deleteEnd();
void addMiddle(int x);
void deleteMiddle();
int count();
};
node::node()
{
head = NULL;
}
node::~node()
{
delete head;
}
void node::addFirst(int x)
{
node *ptr = new node();
if(head == NULL)
{
head = new node();
head->i = x;
head->next = NULL;
}
else
{
ptr->i = x;
ptr->next = head;
head = ptr;
}
}
void node::display()
{
node *ptr = new node();
ptr = head;
while(ptr != NULL)
{
cout<<ptr->i<<" -> ";
ptr = ptr->next;
}
}
void node::deleteFirst()
{
node *temp = new node();
temp = head;
head = temp->next;
delete temp;
}
void node::addEnd(int x)
{
node *ptr = head;
node *newnode = new node();
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newnode;
newnode->i = x;
newnode->next = NULL;
}
void node::deleteMiddle()
{
node *ptr;
ptr = head;
for(int a = 0; a < count()/2; a++)
{
ptr = ptr->next;
}
delete ptr;
}
void node::addMiddle(int x)
{
node *ptr = new node();
ptr = head;
node *nw = new node();
for(int a = 0; a < count()/2; a++)
{
ptr = ptr->next;
}
ptr->i = x;
}
void node::deleteEnd()
{
node *ptr;
ptr = head;
while(ptr->next != NULL)
{
next = ptr;
ptr = ptr->next;
}
next->next = NULL;
}
int node::count()
{
int c=0;
node *ptr = head;
while(ptr != NULL)
{
ptr = ptr->next;
c++;
}
return c;
}
main()
{
node b;
b.addFirst(5);
b.addFirst(3);
b.addFirst(2);
b.addFirst(3);
b.addFirst(4);
b.addFirst(8);
b.addMiddle(1);
cout<<"\n";
b.display();
cout<<endl<<endl<<b.count();
getch();
}