DEV Community

Micken Kasembeli
Micken Kasembeli

Posted on

Q

include

using namespace std;

class Node {
public:
int data;
Node* next;
Node(int d) {
data = d;
next = NULL;
}
};

class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}

void insertAtEnd(int d) {
    Node* newNode = new Node(d);
    if (head == NULL) {
        head = newNode;
        head->next = NULL;
        return;
    }
    Node* temp = head;
    while (temp->next!= NULL) {
        temp = temp->next;
    }
    temp->next = newNode;
}

void deleteNode(int key) {
    if (head == NULL) {
        return;
    }
    Node* temp = head;
    if (temp->data == key) {
        Node* newNode = temp->next;
        delete temp;
        head = newNode;
        return;
    }
    while (temp->next!= NULL && temp->next->data!= key) {
        temp = temp->next;
    }
    if (temp->next == NULL) {
        return;
    }
    Node* newNode = temp->next->next;
    delete temp->next;
    temp->next = newNode;
}

void display() {
    Node* temp = head;
    while (temp!= NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}
Enter fullscreen mode Exit fullscreen mode

};

int main() {
LinkedList llist;
llist.insertAtEnd(10);
llist.insertAtEnd(20);
llist.insertAtEnd(30);
llist.display();
llist.deleteNode(20);
llist.display();
return 0;
}#include
using namespace std;

class Node {
public:
int data;
Node* next;
Node(int d) {
data = d;
next = NULL;
}
};

class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}

void insertAtEnd(int d) {
    Node* newNode = new Node(d);
    if (head == NULL) {
        head = newNode;
        head->next = NULL;
        return;
    }
    Node* temp = head;
    while (temp->next!= NULL) {
        temp = temp->next;
    }
    temp->next = newNode;
}

void deleteNode(int key) {
    if (head == NULL) {
        return;
    }
    Node* temp = head;
    if (temp->data == key) {
        Node* newNode = temp->next;
        delete temp;
        head = newNode;
        return;
    }
    while (temp->next!= NULL && temp->next->data!= key) {
        temp = temp->next;
    }
    if (temp->next == NULL) {
        return;
    }
    Node* newNode = temp->next->next;
    delete temp->next;
    temp->next = newNode;
}

void display() {
    Node* temp = head;
    while (temp!= NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}
Enter fullscreen mode Exit fullscreen mode

};

int main() {
LinkedList llist;
llist.insertAtEnd(10);
llist.insertAtEnd(20);
llist.insertAtEnd(30);
llist.display();
llist.deleteNode(20);
llist.display();
return 0;
}

Top comments (0)