思路(代码在最下面):
这是个用双链表实现双端队列的问题,难点在对双链表操作:
双端队列定义:
typedef struct Node *PtrToNode;
struct Node {
ElementType Element;
PtrToNode Next, Last;
};
typedef struct DequeRecord *Deque;
struct DequeRecord {
PtrToNode Front, Rear;
};
双端队列中有指向首尾的两个指针。注意,Front与头节点地位相同,不存元素。
每个节点包括数据Element 和 Next,Last指针,分别指向下一个节点和上一个节点。
1.创建双端队列
Deque CreateDeque();
(1)创建队列指针,申请空间,为队列中两个指向节点的指针申请空间。
(2)Front 前指针设置NULL ,Rear后指针设置NULL。
(3)Front = Rear,表示链表为空,返回队列指针。
2.在前面插入元素
int Push( ElementType X, Deque D );
(1)申请临时节点 tmp,给Element赋值。
(2)如果原来为空,把tmp赋值给Front的Next(Front是头节点,不存元素),Front赋值给tmp的Last,把tmp赋值给Rear,Rear->Next = NULL。
(3)如果不空,先把tmp连在链上,再让tmp前后节点指向它。
tmp->Next=D->Front->Next;
tmp->Last=D->Front;
D->Front->Next->Last=tmp;
D->Front->Next=tmp;
3.在前面删除
(1).如果为空,返回ERROR。
(2).保存要删除的值num
(3)如果链表中只剩一个元素,让他俩相同。
D->Rear=D->Front;
D->Rear->Next=NULL;
(4)否则让被删除的后一个位置的前指针指向Front,Front的Next指向被删除的后一个位置。
D->Front->Next->Next->Last=D->Front;
D->Front->Next=D->Front->Next->Next;
4.在后面插入元素
(1)申请节点tmp保存元素
(2)如果为空,把tmp赋值给Rear,并且连在Front的Next
(3)否则连在Rear后面。
5.在后面删除
(1)如果为空,返回ERROR。
(2)否则,Rear向前移动一个节点。
代码:
Deque CreateDeque()
{
Deque p;
p=(Deque)malloc(sizeof (struct DequeRecord));
p->Front=(PtrToNode)malloc(sizeof (struct Node));
p->Rear=(PtrToNode)malloc(sizeof (struct Node));
p->Front->Last=NULL;
p->Rear=p->Front;
p->Rear->Next=NULL;
return p;
}
int Push(ElementType X,Deque D)
{
struct Node*tmp;
tmp=(struct Node*)malloc(sizeof(struct Node));
if(!tmp)return 0;
tmp->Element=X;
if(D->Front==D->Rear)
{
D->Front->Next=tmp;
tmp->Last=D->Front;
D->Rear=tmp;
D->Rear->Next=NULL;
return 1;
}
tmp->Next=D->Front->Next;
tmp->Last=D->Front;
D->Front->Next->Last=tmp;
D->Front->Next=tmp;
return 1;
}
ElementType Pop(Deque D)
{
if(D->Front==D->Rear)
return ERROR;
int num=D->Front->Next->Element;
struct Node *tmp=D->Front->Next;
if(D->Front->Next==D->Rear)
{
D->Rear=D->Front;
D->Rear->Next=NULL;
free(tmp);
return num;
}
D->Front->Next->Next->Last=D->Front;
D->Front->Next=D->Front->Next->Next;
free(tmp);
return num;
}
int Inject(ElementType X,Deque D)
{
struct Node* tmp;
tmp=(struct Node*)malloc(sizeof(struct Node));
if(!tmp)return 0;
tmp->Element=X;
if(D->Front==D->Rear)
{
D->Front->Next=tmp;
tmp->Last=D->Front;
D->Rear=tmp;
return 1;
}
D->Rear->Next=tmp;
tmp->Last=D->Rear;
tmp->Next=NULL;
D->Rear=tmp;
return 1;
}
ElementType Eject(Deque D)
{
if(D->Front==D->Rear)
return ERROR;
int num=D->Rear->Element;
struct Node*tmp=D->Rear;
D->Rear=D->Rear->Last;
D->Rear->Next=NULL;
free(tmp);
return num;
}