Write a program using inheritance in C++ to insert a node in the middle of Doubl
ID: 3590397 • Letter: W
Question
Write a program using inheritance in C++ to insert a node in the middle of Doubly linked list .( using this code) but no need for deletion just the insert in the middle using inheritance.
#ifndef DLLIST
#define DLLIST
#include<iostream>
using namespace std;
template<class T>
class DLLNode {
public:
T info;
DLLNode<T> *next, *prev;
DLLNode(){
next = prev = 0;
}
DLLNode(T t, DLLNode<T> *n = 0, DLLNode<T> *p = 0) {
info = t;
next = n;
prev = p;
}
};
template<class T>
class DLL{
protected:
DLLNode<T> *head=0, *tail=0;
public:
void insertAtHead(T t) {
head = new DLLNode<T>(t, head);
if (tail != 0)// if at least two nodes;
//if(head->nexttail!= 0)
head->next->prev = head;
else tail = head;
}
T deleteFromTail() {
//if (head == 0) // in list is empty
//return 0; // in most cases makes no sense;
T t = tail->info; // (*tail).info
tail = tail->prev;
if (tail != 0) {
delete tail->next;
tail->next = 0;
}
else {
delete head;
head = 0;
}
return t;
}
bool isEmpty() {
return head == 0;
}
template<class T>
friend ostream& operator<<(ostream& out, const DLL<T>& dll);
};
template<class T>
ostream& operator<<(ostream& out, const DLL<T>& dll) {
for (DLLNode<T> *p = dll.head; p!= 0; p = p->next)
out << p ->info << ' ';
out << endl;
return out;
}
#include "stdafx.h"
#include "DLL.h"
#include <list>
using namespace std;
void testDLL() {
DLL<int> dll;
dll.insertAtHead(10);
dll.insertAtHead(11);
dll.insertAtHead(12);
cout << dll;
cout << dll.deleteFromTail() << endl;
cout << dll;
cout << dll.deleteFromTail() << endl;
cout << dll;
cout << dll.deleteFromTail() << endl;
cout << dll;
cout << dll.deleteFromTail() << endl;
}
void testSTLlist() {
list <int> lst;
lst.push_back(10);
lst.push_back(20);
lst.push_back(30);
cout << lst << endl;
}
template<class T>
ostream& operator<<(ostream& out, list<T>& lst) {
for (list<T>::iterator i = lst.begin(); i != lst.end(); i++)// overload
out << *i << ' ';
out << endl;
return out;
}
int main()
{
testDLL();
testSTLlist()
return 0;
}
Explanation / Answer
void insertAtMidpos(Node** head_ref, int x)
{
if (*head_ref == NULL)
*head_ref = getNode(x);
else {
Node* newNode = getNode(x);
Node* ptr = *head_ref;
int len = 0;
while (ptr != NULL) {
len++;
ptr = ptr->next;
}
int count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = *head_ref;
while (count-- > 1)
ptr = ptr->next;
newNode->next = ptr->next;
ptr->next = newNode;
}
}
void display(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.