Академический Документы
Профессиональный Документы
Культура Документы
By making enQueue:
enQueue(q, x)
1) While stack1 is not empty, push everything from stack1 to
stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
Here time complexity will be O(n)
deQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Here time complexity will be O(1)
By making deQueue
Page 2 of 8
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
Here time complexity will be O(1)
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from stack1 to
stack2.
3) Pop the element from stack2 and return it.
Here time complexity will be O(n)
struct QNode
int key;
};
// The queue, front stores the front node of LL and rear stores ths
// last node of LL
struct Queue
};
temp->key = k;
temp->next = NULL;
return temp;
return q;
Page 3 of 8
}
// If queue is empty, then new node is front and rear both
{
return;
}
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
return NULL;
// Store previous front and move front one node ahead
q->front = q->front->next;
q->rear = NULL;
return temp;
Page 4 of 8
int Findmax(q)
{
int max_value =0;
int main(){
enQueue(q, 10);
enQueue(q, 20);
deQueue(q);
deQueue(q);
enQueue(q, 30);
enQueue(q, 40);
enQueue(q, 50);
cout<<Findmax(q);
Return 0;
Page 5 of 8
head ← prevNode
End if
End
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next,*prev;
}node;
struct node* head;
void insertAtEnd(int x)
{
struct node* temp=NULL;
temp=(node*)malloc(sizeof(struct node));
temp->data=x;
if(head==NULL)
{
temp->next=NULL;
head=temp;
temp->prev=head;
}
else
{
struct node* temp2=head;
while(temp2->next!=NULL)
{
temp2=temp2->next;
}
temp2->next=temp;
temp->prev=temp2->next;
temp->next=NULL;
Page 7 of 8
}
}
void print()
{
struct node* temp=head;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}
void insertAtAnyPosition(int x,int pos)
{
struct node* temp=NULL;
temp=(node*)malloc(sizeof(struct node));
temp->data=x;
if(head==NULL)
{
temp->next=NULL;
head=temp;
temp->prev=head;
}
else
{
struct node* temp2=head;
struct node* temp3=NULL;
int i=0;
for(i=0;i<pos-1;i++)
{
temp2=temp2->next;
temp3=temp2->next;
}
temp->next=temp3;
temp3->prev=temp->next;
temp2->next=temp;
temp->prev=temp2;
}
printf(" After Insertion at any Position ");
Page 8 of 8
print();
}
void main()
{
insertAtEnd(2);
insertAtEnd(3);
insertAtEnd(9);
insertAtEnd(8);
print();
insertAtAnyPosition(23,3);
getch();
}