0% found this document useful (0 votes)
18 views2 pages

A2 Ques2

Data structures practicals

Uploaded by

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

A2 Ques2

Data structures practicals

Uploaded by

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

/*Q2.

Describe a non-recursive function for displaying, by link


hopping, the middle node element of a doubly linked list
(Note: This function must only use link hopping; it cannot use
a counter.) What is the running time of this function? If the
list contains even number of nodes then the function should
display the middle two elements.*/
#include <iostream>
using namespace std;
template <class T>
class node
{
private:
node<T> *prev;
T value;
node<T> *next;
public:
node(T x=0,node<T> *n=0,node<T> *p=0)
{
value=x;
next=n;
prev=p;
}
template <class X> friend class doubly_linked_list;
};
template <class T>
class doubly_linked_list
{
private:
node<T> *head;
node<T> *tail;
int count;
public:
doubly_linked_list()
{
head=0;
tail=0;
count=0;
}
~doubly_linked_list()
{
while (head!=0)
{
node<T> *p=head;
head=head->next;
delete p;
count--;
}
}
void display()
{
node<T> *p=head;
for (int i=0;i<count;i++)
{
cout<<p->value;
p=p->next;
if (i!=count-1)
{
cout<<",";
}
}
cout<<endl;
}
void add_front(T x)
{
node<T> *p = new node<T>(x);
p->next=head;
head=p;
if (tail==0)
{
tail=head;
}
count++;
}
void add_last(T x)
{
node<T> *p=new node<T>(x);
p->prev=tail;
tail->next=p;
tail=tail->next;
if (head==0)
{
head=tail;
}
count++;
}
void add_ith(T x,int index)
{
node<T> *p=head;
for(int i=1;i<index-1;i++)
{
p=p->next;
}
node<T> *q=new node<T>(x);
q->prev=p;
q->next=p->next;
p->next=q;
q->next->prev=q;
count++;
}
void middle_element() // Time Complexity = O(n/2) ~ O(n)
{
node<T> *start=head;
node<T> *end=tail;
while(head!=0)
{
if (start==end)
{
cout<<"Middle Element is : "<<start->value<<endl;
break;
}
else if(start->next==end)
{
cout<<"Middle Elements are : "<<start->value<<" and "<<end->value<<endl;
break;
}
else
{
start=start->next;
end=end->prev;
}
}
}
};
int main()
{
doubly_linked_list<int> list1;
list1.add_front(2);
list1.add_last(4);
list1.add_ith(3,2);
list1.add_front(1);
list1.add_last(5);
//list1.add_last(6);
list1.display();
list1.middle_element();
return 0;
}

You might also like