Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class node{
- protected:
- int element;
- node* link;
- public:
- //constructor that accepts only element
- node(int element) {
- this->element = element;
- this->link = NULL;
- }
- //constructor that accepts both link and element
- node(int element, node* link){
- this->element = element;
- this->link = link;
- }
- //method to update the element
- void updateData(int element){
- this->element = element;
- }
- //method to update or setup link
- void updateLink(node* link){
- this->link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this->element;
- }
- //method to get the next node
- node* getNextNode(){
- return this->link;
- }
- };
- class Linkedlist{
- protected:
- node* head;
- public:
- //constructor for the Linked List class
- Linkedlist(){
- head = NULL;
- }
- //method returns true if the list is empty
- bool isEmpty(){
- return head == NULL;
- }
- //returns head node
- node* getHead(){
- return this->head;
- }
- //method to add a node at starting
- void addToStart(int element){
- node* tempNode = new node(element);
- if(head == NULL){
- head = tempNode;
- }
- else{
- tempNode->updateLink(head);
- head = tempNode;
- }
- }
- // method to add a node at the end
- void addToEnd(int element){
- node* tempNode = new node(element);
- node* p = head;
- if(head == NULL){
- head = tempNode;
- return;
- }
- else{
- while(p->getNextNode()!= NULL){
- p = p->getNextNode();
- }
- p->updateLink(tempNode);
- return;
- }
- }
- //method to display all the elements of the Linked List
- void display(){
- cout<<"\n";
- node* tempNode = head;
- while(tempNode != NULL){
- if(tempNode->getNextNode() != NULL)
- cout<<tempNode->getElement()<<" --> ";
- else
- cout<<tempNode->getElement();
- tempNode = tempNode->getNextNode();
- }
- return;
- }
- //method that returns the length of the Linked List
- int length(){
- int count = 0;
- if(this->isEmpty()){
- return -1;
- }
- node* tempNode = head;
- while(tempNode != NULL){
- count += 1;
- tempNode = tempNode->getNextNode();
- }
- return count;
- }
- //method to delete a data element
- void deleteData(int element){
- if(isEmpty()){
- cout<<"The List is Empty";
- return;
- }
- else{
- node* tempNode = head;
- node* prevNode = head;
- while(tempNode->getElement() != element){
- prevNode = tempNode;
- tempNode = tempNode->getNextNode();
- }
- prevNode->updateLink(tempNode->getNextNode());
- return;
- }
- }
- };
- int main() {
- Linkedlist l1;
- l1.addToStart(25);
- l1.addToStart(25);
- l1.addToStart(25);
- l1.addToStart(26);
- l1.addToStart(27);
- l1.addToStart(28);
- l1.display();
- l1.addToEnd(24);
- l1.addToEnd(23);
- cout<<"\n";
- l1.display();
- l1.deleteData(26);
- l1.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment