Code:
#include<iostream>
using namespace std;
class ll{
public:
int val;
ll*prev;
ll* next;
ll(int value){
val=value;
prev=NULL;
next=NULL;
}
};
void push_front(int value,ll*&head,ll*&tail){
ll*temp= new ll(value);
if(!head){
head=temp;
tail=temp;
return;
}
temp->next=head;
head->prev=temp;
head=temp;
}
void push_back(int value,ll *&head,ll*&tail){
ll*temp=new ll(value);
if(!head){
head=temp;
tail=temp;
return;
}
tail->next=temp;
temp->prev=tail;
tail=temp;
}
void pop_back(ll*&head,ll*&tail){
if(!head) {
cout<<"nothing to delete";
return;
}
if(tail->prev){
tail=tail->prev;
tail->next=NULL;
return;
}
head=NULL;
tail=NULL;
}
void pop_front(ll*&head,ll*&tail){
if(!head){
cout<<"nothing to del";
return;
}
if(head->next){
head=head->next;
head->prev=NULL;
return;
}
head=tail=NULL;
}
void print(ll*head){
while(head){
cout<<head->val<<" ";
head=head->next;
}
cout<<endl;
}
int main(){
ll*head=NULL;
ll* tail=NULL;
push_front(67,head,tail);
push_front(66,head,tail);
push_front(65,head,tail);
print(head);
push_back(68,head,tail);
push_back(69,head,tail);
pop_back(head,tail);
pop_front(head,tail);
pop_front(head,tail);
pop_front(head,tail);
pop_front(head,tail);
pop_front(head,tail);
print(head);
}
Complexities:
push O(1)
pop O(1)
travesrsal O(n)
No comments:
Post a Comment