implement deque using linked list

来源:互联网 发布:北京域名快速备案 编辑:程序博客网 时间:2024/04/28 00:26

implement the follwing operation

push(x,d): Insert item x on the front end of deque d.

pop(d): Remove the front item from deque d and return it.

inject(x,d): Insert item x on the rear end of deque d.

eject(d): Remove the rear item from deque d and return it.

#include <stdio.h>
#include <stdlib.h>
//implement dequeue with linked list
typedef struct node
{
int data;
struct node *link;
}node;
typedef struct dequeue
{
node *front;
node *rear;
}dequeue;
void initqueue(dequeue *q,int ele)
{
q->front=q->rear=NULL;
}
void push(dequeue *q,int ele)//Insert item x on the front end of deque d.
{
node *temp;
int *p;
temp=(node *)malloc(sizeof(node));
if(temp){
temp->data=ele;
temp->link=NULL;
if(q->front==NULL){
q->front=q->rear=temp;
}
else{
temp->link=q->front;
q->front=temp;
}
}
else{
fprintf(stderr, "insufficient memroy for new node\n");
}
}
int pop(dequeue *q)//Remove the front item from deque d and return it.
{
if(q->front){
node *temp=q->front;
int ele=temp->data;
q->front=temp->link;
free(temp);
if(q->front==NULL){
q->rear=NULL;
}
temp=NULL;
return ele;
}
else{
fprintf(stderr, "dequeue is empty!\n");
return 0;
}
}
void inject(dequeue *q,int ele)//Insert item x on the rear end of deque d.
{
node *temp;
temp=(node *)malloc(sizeof(node));
if(temp){
temp->data=ele;
temp->link=NULL;
if(q->front==NULL){
q->front=temp;
}
else{
q->rear->link=temp;
}
q->rear=temp;
}
else{
fprintf(stderr, "insufficient memory for new node\n");
exit(1);
}
}
void eject(dequeue *q)//Remove the rear item from deque d and return it.
{
if(q->rear){
int ele=q->rear->data;
if(q->rear==q->front){
free(q->rear);
q->rear=q->front=NULL;
}
else{
node *temp=q->front;
while(temp->link!=q->rear){
temp=temp->link;
}
q->rear=temp;
temp->link=NULL;
temp=NULL;
}
return ele;
}
else{
fprintf(stderr, "dequeue is empty!\n");
return;
}
}


0 0