0% found this document useful (0 votes)
11 views3 pages

Activity 2

Uploaded by

Thypon Live
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Activity 2

Uploaded by

Thypon Live
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

struct Node {

int data;

Node* prev;

Node* next;

Node(int val) : data(val), prev(nullptr), next(nullptr) {}

};

class DoublyLinkedList {

private:

Node* head;

Node* tail;

public:

DoublyLinkedList() : head(nullptr), tail(nullptr) {}

void append(int value) {

Node* newNode = new Node(value);

if (!head) {

head = tail = newNode;

} else {

tail->next = newNode;

newNode->prev = tail;

tail = newNode;

}
void removeFirst() {

if (!head) return; // Empty list

Node* temp = head;

if (head == tail) { // Only one node in the list

head = tail = nullptr;

} else {

head = head->next;

head->prev = nullptr;

delete temp;

void removeLast() {

if (!tail) return; // Empty list

Node* temp = tail;

if (head == tail) { // Only one node in the list

head = tail = nullptr;

} else {

tail = tail->prev;

tail->next = nullptr;

delete temp;

void display() {

Node* current = head;

while (current) {

std::cout << current->data << " -> ";


current = current->next;

std::cout << "nullptr" << std::endl;

};

int main() {

DoublyLinkedList list;

list.append(1);

list.append(2);

list.append(3);

list.append(4);

list.append(5);

std::cout << "Original List:" << std::endl;

list.display();

list.removeFirst();

std::cout << "\nAfter removing first node:" << std::endl;

list.display();

list.removeLast();

std::cout << "\nAfter removing last node:" << std::endl;

list.display();

return 0; // Corrected return statement

You might also like