試解leetcode算法題--設計循環雙端隊列

<題目描述>
設計實現雙端隊列,支持以下操作:
MyCircularDeque(k):構造函數,雙端隊列的大小爲k。
insertFront():將一個元素添加到雙端隊列頭部。 如果操作成功返回 true。
insertLast():將一個元素添加到雙端隊列尾部。如果操作成功返回 true。
deleteFront():從雙端隊列頭部刪除一個元素。 如果操作成功返回 true。
deleteLast():從雙端隊列尾部刪除一個元素。如果操作成功返回 true。
getFront():從雙端隊列頭部獲得一個元素。如果雙端隊列爲空,返回 -1。
getRear():獲得雙端隊列的最後一個元素。 如果雙端隊列爲空,返回 -1。
isEmpty():檢查雙端隊列是否爲空。
isFull():檢查雙端隊列是否滿了。
<原題鏈接>
https://leetcode-cn.com/problems/design-circular-deque/
<理明思路>
使用鏈表來實現雙端循環隊列
<樣例代碼>

#include<iostream>
using namespace std;
class MyCircularDeque {
public:
	/** Initialize your data structure here. Set the size of the deque to be k. */
	MyCircularDeque(int k)
	{
		deque_size = k;
		p = NULL;
		head = NULL;
		tail = NULL;
	}

	/** Adds an item at the front of Deque. Return true if the operation is successful. */
	bool insertFront(int value) 
	{
		if (isFull())
			return false;
		p = new Deque;
		p->x = value;
		p->next = NULL;
		if (isEmpty())
		{
			head = p;
			tail = p;
			head->next = tail;
			tail->next = head;
		}
		else
		{
			p->next = head;
			head = p;
			tail->next = p;
		}
		return true;
	}

	/** Adds an item at the rear of Deque. Return true if the operation is successful. */
	bool insertLast(int value) 
	{
		if (isFull())
			return false;
		p = new Deque;
		p->x = value;
		p->next = NULL;
		if (isEmpty())
		{
			head = p;
			tail = p;
			head->next = tail;
			tail->next = head;
		}
		else
		{
			tail->next = p;
			p->next = head;
			tail = p;
		}
		return true;
	}

	/** Deletes an item from the front of Deque. Return true if the operation is successful. */
	bool deleteFront()
	{
		if (isEmpty())
			return false;
		Deque * t;
		if (head == tail)
		{
			delete head;
			head = NULL;
			tail = NULL;
		}
		else
		{
			t = head->next;
			tail->next = t;
			delete head;
			head = t;
		}
		return true;
	}

	/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
	bool deleteLast() 
	{
		if (isEmpty())
			return false;
		Deque * t;
		if (head == tail)
		{
			delete tail;
			head = NULL;
			tail = NULL;
		}
		else
		{
			for (t = head; t->next != tail; t = t->next);
			t->next = head;
			delete tail;
			tail = t;
		}
		return true;
	}

	/** Get the front item from the deque. */
	int getFront() 
	{
		if (isEmpty())
			return -1;
		return head->x;
	}

	/** Get the last item from the deque. */
	int getRear() 
	{
		if (isEmpty())
			return -1;
		return tail->x;
	}

	/** Checks whether the circular deque is empty or not. */
	bool isEmpty() 
	{
		if (head == NULL)
			return true;
		return false;
	}

	/** Checks whether the circular deque is full or not. */
	bool isFull() 
	{
		Deque * t;
		int _count = 0;
		for (t = head; t != tail; t = t->next)
			_count++;
		++_count;
		return _count == deque_size;
	}
private:
	unsigned int deque_size;
	struct Deque
	{
		int x;
		struct Deque * next;
	}*p, *head, *tail;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章