I. Question
Write a routine that supports double-end queues. It takes O (1) Time for insertion and pop-up operations.
Ii. Answers
A double-ended Queue (deque) is a data structure with queues and stacks.
Elements in a dual-end queue can pop up from both ends. The insert and delete operations are limited to both sides of the queue.
Basic operation: insert and delete two ends of the double-end queue.
ADT terminology:
Capacity: array capacity
Left: left end of the queue, pointing to the first element on the left of the queue
Right: Right of the queue, pointing to the next position of the last element on the right of the queue
Initialization: Left = right = 0;
Empty: Left = right
Sentence full: (left-1) % capacity = right
Iii. Code
Struct dequerecord; typedef struct dequerecord * deque; struct dequerecord {int capacity; int left; int right; elementtype * array;}; deque createdeque (INT maxelements ); int isempty (deque D); int isfull (deque D); void makeempty (deque D); void push_left (elementtype X, deque D); void push_right (elementtype X, deque D); elementtype pop_left (deque D); elementtype pop_right (deque D); void disposedequ E (deque D); deque createdeque (INT maxelements) {deque D; D = (deque) malloc (sizeof (struct dequerecord); If (D = NULL) {printf ("out of space"); return NULL;} D-> array = (elementtype *) malloc (sizeof (elementtype) * maxelements ); if (D-> array = NULL) {printf ("out of space"); return NULL;} D-> capacity = maxelements; makeempty (d); Return D ;} int isempty (deque d) {return D-> left = = D-> right;} int isfull (deque d) {return (D-> left + D-> capacity-1) % d-> capacity = D-> right;} void makeempty (deque d) {d-> left = 0; D-> right = 0 ;} void push_left (elementtype X, deque d) {If (isfull (D) printf ("Full deque "); else {d-> left = (D-> left-1 + D-> capacity) % d-> capacity; d-> array [D-> left] = x ;}} void push_right (elementtype X, deque d) {If (isfull (D) printf ("Full DEQ Ue "); else {d-> array [D-> right] = x; D-> right = (D-> right + 1) % d-> capacity ;}} elementtype pop_left (deque d) {elementtype tmpcell; If (isempty (D) {printf ("Empty deque"); Return 0; // invalid element should be returned} else {tmpcell = D-> array [D-> left]; D-> left = (D-> left + 1) % d-> capacity;} return tmpcell;} elementtype pop_right (deque d) {elementtype tmpcell; If (isempty (D) {printf ("Empty deque "); Return 0;} else {d-> right = (D-> right-1 + D-> capacity) % d-> capacity; tmpcell = D-> array [D-> right];} return tmpcell;} void disposedeque (deque d) {If (D! = NULL) {free (D-> array); free (d );}}
Data Structure and algorithm analysis 3.26-Implementation of Dual-end queue