题目解读:
使用堆栈实现以下操作:
1.push(x):将元素x加入队列
2.pop():取出第一个元素
3.peek():求第一个元素的值
4.empty():判空操作
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
解题思路:
该题的主要是要实现题目要求的函数; 我将在代码中通过注释详细说明。
注意点:在对队列进行操作时,如果有遇到结点的增添,删除等等操作时,要注意结点数据结构的完整性,即要对数据结构中的每个元素进行操作。
c代码(含注释):
typedef struct MyQueueData;
typedef struct QueueData {//数据结构
int data;//数据
struct QueueData* next;//下一个数据的位置
struct QueueData* prev;//上一个数据的位置
} MyQueueData;
typedef struct {
MyQueueData* head;//队头元素的位置
MyQueueData* tail;//队尾元素的位置
int size;//队列当前的长度
int maxSize;//队列的最大长度
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate(int maxSize) {
MyQueue* queue = (MyQueue*) malloc(sizeof(MyQueue));//动态创建队列空间
memset(queue, 0, sizeof(MyQueue));//初始化
queue->maxSize = maxSize;//设置数组的最大长度
return queue;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
if (obj->size == obj->maxSize) {//如果当前长度等于最大长度,则执行空操作
return;
}
MyQueueData* Data = (MyQueueData*) malloc(sizeof(MyQueueData));//创建新的数据空间
memset(Data, 0, sizeof(MyQueueData))//初始化data;
Data->data = x;//将x赋值于data
if (obj->size > 0) {//当obj的长度为空时,将Data加入队列末尾,并将尾指针指向Data
Data->prev = obj->tail;
Data->prev->next =Data;
obj->tail = Data;
}
else {//当obj的长度不为空时,头指针于尾指针都指向Data
obj->head = Data;
obj->tail = Data;
}
++obj->size;//obj的长度加1
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
if (obj->size == 0) {//如果当前长度等于最大长度,则返回0;
return 0;
}
MyQueueData* head = obj->head;//找到obj的第一个元素的指针
int data = head->data;//将第一个元素的数据赋值给data
if (head->next) {//如果head的下一个地址存在
head->next->prev = 0;//将下一个地址的pre置为空
}
obj->head = head->next;//head指针指向head的下一个地址
free(head);//释放head的空间
--obj->size;//obj的长度减1
return data;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
if (obj->size == 0) {//如果当前长度等于0,返回0;
return 0;
}
return obj->head->data;//否则返回第一个结点的data值
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
return obj->size == 0;//如果当前长度等于false,否则返回true
}
void myQueueFree(MyQueue* obj) {//清空队列操作
while (obj->head) {//如果头指针为空,则循环继续
MyQueueData* next = obj->head->next;//找到下一个地址
free(obj->head);//释放头指针
obj->head = next;//头指针指向下一个地址
}
free(obj);//释放obj
}
/**
* Your MyQueue struct will be instantiated and called as such:
* struct MyQueue* obj = myQueueCreate(maxSize);
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/