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
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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started