- #1
needOfHelpCMath
- 72
- 0
Yea! I was able to code my own first SINGLE LINKED LIST! but having a little issues with my deleting middle. As you can see if you take my code run it.
My output:View attachment 6429
It will give me this:
HTML:
#include<iostream>
using namespace std;
class Node {
public:
int Nodedata;
Node *next;
Node() {next = NULL; Nodedata = 0;}
Node(int data, Node *nextNode) { //overloaded constructor
Nodedata = data;
next = nextNode;
}
};
// traverse printing all the elements
class SLL {
public:
Node *front;
Node *counter;
// part D Traverse the SLL and print all the elements out
void print(Node *nn) {
while (nn != NULL) {
cout << nn->Nodedata << " ";
nn = nn->next;
}
}
// part E delete last node
void deleteback(Node *nn) {
while (nn->next->next != NULL) {
nn = nn->next;
}
delete nn->next;
nn->next = NULL;
}
//part F will tranverse in the middle and delete the middle
void deleteMiddle (Node *nn) {
Node *y_ptr = nn; // will intialize y and z pointers to reach the middle of the linked list
Node *z_ptr = nn;
Node *prev;
if (nn == NULL) {
return;
}
if (nn->next == NULL) {
delete nn;
return;
}
while (z_ptr != NULL && z_ptr->next != NULL) {
z_ptr = z_ptr->next->next;
prev = y_ptr;
y_ptr = y_ptr->next;
}
prev->next = y_ptr->next;
delete y_ptr->next;
}
};
int main() {
// part A
Node *a;
a = new Node(1,NULL);
Node *b;
b = new Node(2,NULL);
Node *c;
c = new Node(4,NULL);
Node *d;
d = new Node(6,NULL);
Node *e;
e = new Node(8,NULL);
Node *f;
f = new Node(9,NULL); // insert at the beginning of Node *a;
Node *g;
g = new Node(10,NULL); // insert in the middle
f->next = a;
a->next = b;
b->next = c;
c->next = d;
d->next = e;
c->next = g;
g->next = d;
SLL list; // object of the class SLL and part D
list.print(f);
// part E deleting the last element
list.deleteback(f);
cout << endl;
list.print(f);
// part F
list.deleteMiddle(f);
cout << endl;
list.print(f);
return 0;
}
It will give me this: