6-1-Deque-函数题

6-1-Deque-函数题

解题代码

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。
发布了47 篇原创文章 · 获赞 2 · 访问量 1333

猜你喜欢

转载自blog.csdn.net/Aruasg/article/details/105215032