Update cpp codes for the stack and the queue.

This commit is contained in:
Yudong Jin 2023-01-05 01:45:08 +08:00
parent 01e211c7ee
commit 3302354909
4 changed files with 12 additions and 16 deletions

View file

@ -50,11 +50,10 @@ public:
} }
/* 出队 */ /* 出队 */
int poll() { void poll() {
int num = peek(); int num = peek();
// 队头指针向后移动一位,若越过尾部则返回到数组头部 // 队头指针向后移动一位,若越过尾部则返回到数组头部
front = (front + 1) % capacity(); front = (front + 1) % capacity();
return num;
} }
/* 访问队首元素 */ /* 访问队首元素 */
@ -98,8 +97,8 @@ int main() {
cout << "队首元素 peek = " << peek << endl; cout << "队首元素 peek = " << peek << endl;
/* 元素出队 */ /* 元素出队 */
int poll = queue->poll(); queue->poll();
cout << "出队元素 poll = " << poll << ",出队后 queue = "; cout << "出队元素 poll = " << peek << ",出队后 queue = ";
PrintUtil::printVector(queue->toVector()); PrintUtil::printVector(queue->toVector());
/* 获取队列的长度 */ /* 获取队列的长度 */

View file

@ -28,10 +28,9 @@ public:
} }
/* 出栈 */ /* 出栈 */
int pop() { void pop() {
int oldTop = top(); int oldTop = top();
stack.pop_back(); stack.pop_back();
return oldTop;
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
@ -67,8 +66,8 @@ int main() {
cout << "栈顶元素 top = " << top << endl; cout << "栈顶元素 top = " << top << endl;
/* 元素出栈 */ /* 元素出栈 */
int pop = stack->pop(); stack->pop();
cout << "出栈元素 pop = " << pop << ",出栈后 stack = "; cout << "出栈元素 pop = " << top << ",出栈后 stack = ";
PrintUtil::printVector(stack->toVector()); PrintUtil::printVector(stack->toVector());
/* 获取栈的长度 */ /* 获取栈的长度 */

View file

@ -47,7 +47,7 @@ public:
} }
/* 出队 */ /* 出队 */
int poll() { void poll() {
int num = peek(); int num = peek();
// 删除头结点 // 删除头结点
ListNode *tmp = front; ListNode *tmp = front;
@ -55,7 +55,6 @@ public:
// 释放内存 // 释放内存
delete tmp; delete tmp;
queSize--; queSize--;
return num;
} }
/* 访问队首元素 */ /* 访问队首元素 */
@ -97,8 +96,8 @@ int main() {
cout << "队首元素 peek = " << peek << endl; cout << "队首元素 peek = " << peek << endl;
/* 元素出队 */ /* 元素出队 */
int poll = queue->poll(); queue->poll();
cout << "出队元素 poll = " << poll << ",出队后 queue = "; cout << "出队元素 poll = " << peek << ",出队后 queue = ";
PrintUtil::printVector(queue->toVector()); PrintUtil::printVector(queue->toVector());
/* 获取队列的长度 */ /* 获取队列的长度 */

View file

@ -37,14 +37,13 @@ public:
} }
/* 出栈 */ /* 出栈 */
int pop() { void pop() {
int num = top(); int num = top();
ListNode *tmp = stackTop; ListNode *tmp = stackTop;
stackTop = stackTop->next; stackTop = stackTop->next;
// 释放内存 // 释放内存
delete tmp; delete tmp;
stkSize--; stkSize--;
return num;
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
@ -86,8 +85,8 @@ int main() {
cout << "栈顶元素 top = " << top << endl; cout << "栈顶元素 top = " << top << endl;
/* 元素出栈 */ /* 元素出栈 */
int pop = stack->pop(); stack->pop();
cout << "出栈元素 pop = " << pop << ",出栈后 stack = "; cout << "出栈元素 pop = " << top << ",出栈后 stack = ";
PrintUtil::printVector(stack->toVector()); PrintUtil::printVector(stack->toVector());
/* 获取栈的长度 */ /* 获取栈的长度 */