Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Information Modeling And Relational Databases

Authors: Terry Halpin, Tony Morgan

2nd Edition

0123735688, 978-0123735683

More Books

Students also viewed these Databases questions

Question

Identify sustainable HRM practices in an organization.

Answered: 1 week ago

Question

=+What sanctions are available to employers

Answered: 1 week ago

Question

=+ If strikes occur, are they legally regulated?

Answered: 1 week ago

Question

=+industrial action Under what circumstances can unions strike?

Answered: 1 week ago