解题代码
Deque CreateDeque() {
PtrToNode node = (PtrToNode)malloc(sizeof(struct Node));
node->Next = NULL;
node->Last = NULL;
Deque A = (Deque)malloc(sizeof(struct DequeRecord));
A->Front = node;
A->Rear = node;
return A;
}
int Push(ElementType X, Deque D) {
PtrToNode node = (PtrToNode)malloc(sizeof(struct Node));
if (node)
{
node->Element = X;
if (D->Front == D->Rear) {
node->Last = D->Front;
node->Next = NULL;
D->Front->Next = node;
D->Rear = node;
}
else {
node->Last = D->Front;
node->Next = D->Front->Next;
D->Front->Next = node;
node->Next->Last = node;
}
return 1;
}
else return 0;
}
ElementType Pop(Deque D) {
PtrToNode T = D->Front->Next;
if (!T) return ERROR;
else if(D->Front->Next==D->Rear){
D->Front->Next = NULL;
D->Rear = D->Front;
ElementType temp = T->Element;
free(T);
return temp;
}
else {
D->Front->Next = T->Next;
T->Next->Last = D->Front;
ElementType temp = T->Element;
free(T);
return temp;
}
}
int Inject(ElementType X, Deque D) {
PtrToNode node = (PtrToNode)malloc(sizeof(struct Node));
if (node) {
node->Element = X;
node->Next = NULL;
node->Last = D->Rear;
D->Rear->Next = node;
D->Rear = node;
return 1;
}
else return 0;
}
ElementType Eject(Deque D) {
PtrToNode T = D->Rear;
if (D->Front == D->Rear) return ERROR;
else {
ElementType temp = T->Element;
if (D->Front->Next == D->Rear) {
D->Front->Next = NULL;
D->Rear = D->Front;
}
else {
D->Rear = D->Rear->Last;
D->Rear->Next = NULL;
}
free(T);
return temp;
}
}
测试结果
问题整理
1.别忘记了return。
2.及时更新rear。