Question: For a doubly linked list, implement the following operations. Then test it in the main function. insertAfter(int key,int toInsert) The code for this: #include pch.h

For a doubly linked list, implement the following operations. Then test it in the main function.

insertAfter(int key,int toInsert)

The code for this:

#include "pch.h" #include using namespace std; class DoublyLinkedList { private: struct Node { int data; Node *next; Node *prev;

Node() { data = 0; next = nullptr; prev = nullptr; } Node(int initData, Node *initPrev,Node *initNext) { data = initData; prev = initPrev; next = initNext; } };

Node *head = nullptr; Node *tail = nullptr; int listSize = 0;

public: void addFirst(int key) { Node *tmp = new Node(key, nullptr,head); head = tmp; listSize++; }

int insertBefore(int key, int toInsert) { if (head == nullptr) return -1; if (head->data == key) { addFirst(toInsert); return 0; }

Node *prev = nullptr; Node *cur = head;

while (cur != nullptr && cur->data != key) { prev = cur; cur = cur->next; } //Insert between cur and prev if (cur != nullptr) { Node *newNode; newNode= new Node(toInsert, prev, cur); prev->next = newNode; cur->prev = newNode; listSize++; return 0; } else { return -1; } }

int remove(int key) { if (head == nullptr) { cout << "The list is empty" << endl; return -1; } if (head->data == key) { head = head->next; return 0; }

Node *cur = head; Node *prv = nullptr; Node *nxt = cur->next;

while (cur != nullptr && cur->data != key) { prv = cur; cur = cur->next; nxt = cur->next; }

if (cur == nullptr) { cout << "The key not exsit in the list" << endl; return -1; }

//delete cur node prv->next = cur->next; if (nxt != nullptr) { nxt->prev = prv; } return 0;

}

void printList() { Node *tmp = head;

while (tmp != nullptr) { cout << tmp->data << "->"; tmp = tmp->next; }

cout << endl; } };

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!