This commit is contained in:
krahets
2024-05-06 14:40:36 +08:00
parent 7e7eb6047a
commit 5c7d2c7f17
54 changed files with 3456 additions and 215 deletions

View File

@@ -4,7 +4,7 @@ comments: true
# 5.3   Double-ended queue
In a queue, we can only delete elements from the head or add elements to the tail. As shown in the following diagram, a <u>double-ended queue (deque)</u> offers more flexibility, allowing the addition or removal of elements at both the head and the tail.
In a queue, we can only delete elements from the head or add elements to the tail. As shown in Figure 5-7, a <u>double-ended queue (deque)</u> offers more flexibility, allowing the addition or removal of elements at both the head and the tail.
![Operations in double-ended queue](deque.assets/deque_operations.png){ class="animation-figure" }
@@ -390,7 +390,7 @@ The implementation code is as follows:
def __init__(self, val: int):
"""Constructor"""
self.val: int = val
self.next: ListNode | None = None # Reference to the next node
self.next: ListNode | None = None # Reference to successor node
self.prev: ListNode | None = None # Reference to predecessor node
class LinkedListDeque:
@@ -496,9 +496,146 @@ The implementation code is as follows:
=== "C++"
```cpp title="linkedlist_deque.cpp"
[class]{DoublyListNode}-[func]{}
/* Double-linked list node */
struct DoublyListNode {
int val; // Node value
DoublyListNode *next; // Pointer to successor node
DoublyListNode *prev; // Pointer to predecessor node
DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) {
}
};
[class]{LinkedListDeque}-[func]{}
/* Double-ended queue class based on double-linked list */
class LinkedListDeque {
private:
DoublyListNode *front, *rear; // Front node front, back node rear
int queSize = 0; // Length of the double-ended queue
public:
/* Constructor */
LinkedListDeque() : front(nullptr), rear(nullptr) {
}
/* Destructor */
~LinkedListDeque() {
// Traverse the linked list, remove nodes, free memory
DoublyListNode *pre, *cur = front;
while (cur != nullptr) {
pre = cur;
cur = cur->next;
delete pre;
}
}
/* Get the length of the double-ended queue */
int size() {
return queSize;
}
/* Determine if the double-ended queue is empty */
bool isEmpty() {
return size() == 0;
}
/* Enqueue operation */
void push(int num, bool isFront) {
DoublyListNode *node = new DoublyListNode(num);
// If the list is empty, make front and rear both point to node
if (isEmpty())
front = rear = node;
// Front enqueue operation
else if (isFront) {
// Add node to the head of the list
front->prev = node;
node->next = front;
front = node; // Update head node
// Rear enqueue operation
} else {
// Add node to the tail of the list
rear->next = node;
node->prev = rear;
rear = node; // Update tail node
}
queSize++; // Update queue length
}
/* Front enqueue */
void pushFirst(int num) {
push(num, true);
}
/* Rear enqueue */
void pushLast(int num) {
push(num, false);
}
/* Dequeue operation */
int pop(bool isFront) {
if (isEmpty())
throw out_of_range("Queue is empty");
int val;
// Front dequeue operation
if (isFront) {
val = front->val; // Temporarily store the head node value
// Remove head node
DoublyListNode *fNext = front->next;
if (fNext != nullptr) {
fNext->prev = nullptr;
front->next = nullptr;
}
delete front;
front = fNext; // Update head node
// Rear dequeue operation
} else {
val = rear->val; // Temporarily store the tail node value
// Remove tail node
DoublyListNode *rPrev = rear->prev;
if (rPrev != nullptr) {
rPrev->next = nullptr;
rear->prev = nullptr;
}
delete rear;
rear = rPrev; // Update tail node
}
queSize--; // Update queue length
return val;
}
/* Front dequeue */
int popFirst() {
return pop(true);
}
/* Rear dequeue */
int popLast() {
return pop(false);
}
/* Access front element */
int peekFirst() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
return front->val;
}
/* Access rear element */
int peekLast() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
return rear->val;
}
/* Return array for printing */
vector<int> toVector() {
DoublyListNode *node = front;
vector<int> res(size());
for (int i = 0; i < res.size(); i++) {
res[i] = node->val;
node = node->next;
}
return res;
}
};
```
=== "Java"
@@ -507,7 +644,7 @@ The implementation code is as follows:
/* Double-linked list node */
class ListNode {
int val; // Node value
ListNode next; // Reference to the next node
ListNode next; // Reference to successor node
ListNode prev; // Reference to predecessor node
ListNode(int val) {
@@ -837,7 +974,112 @@ The implementation only needs to add methods for "front enqueue" and "rear deque
=== "C++"
```cpp title="array_deque.cpp"
[class]{ArrayDeque}-[func]{}
/* Double-ended queue class based on circular array */
class ArrayDeque {
private:
vector<int> nums; // Array used to store elements of the double-ended queue
int front; // Front pointer, pointing to the front element
int queSize; // Length of the double-ended queue
public:
/* Constructor */
ArrayDeque(int capacity) {
nums.resize(capacity);
front = queSize = 0;
}
/* Get the capacity of the double-ended queue */
int capacity() {
return nums.size();
}
/* Get the length of the double-ended queue */
int size() {
return queSize;
}
/* Determine if the double-ended queue is empty */
bool isEmpty() {
return queSize == 0;
}
/* Calculate circular array index */
int index(int i) {
// Implement circular array by modulo operation
// When i exceeds the tail of the array, return to the head
// When i exceeds the head of the array, return to the tail
return (i + capacity()) % capacity();
}
/* Front enqueue */
void pushFirst(int num) {
if (queSize == capacity()) {
cout << "Double-ended queue is full" << endl;
return;
}
// Move the front pointer one position to the left
// Implement front crossing the head of the array to return to the tail by modulo operation
front = index(front - 1);
// Add num to the front
nums[front] = num;
queSize++;
}
/* Rear enqueue */
void pushLast(int num) {
if (queSize == capacity()) {
cout << "Double-ended queue is full" << endl;
return;
}
// Calculate rear pointer, pointing to rear index + 1
int rear = index(front + queSize);
// Add num to the rear
nums[rear] = num;
queSize++;
}
/* Front dequeue */
int popFirst() {
int num = peekFirst();
// Move front pointer one position backward
front = index(front + 1);
queSize--;
return num;
}
/* Rear dequeue */
int popLast() {
int num = peekLast();
queSize--;
return num;
}
/* Access front element */
int peekFirst() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
return nums[front];
}
/* Access rear element */
int peekLast() {
if (isEmpty())
throw out_of_range("Double-ended queue is empty");
// Calculate rear element index
int last = index(front + queSize - 1);
return nums[last];
}
/* Return array for printing */
vector<int> toVector() {
// Only convert elements within valid length range
vector<int> res(queSize);
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[index(j)];
}
return res;
}
};
```
=== "Java"

View File

@@ -411,7 +411,81 @@ Below is the code for implementing a queue using a linked list:
=== "C++"
```cpp title="linkedlist_queue.cpp"
[class]{LinkedListQueue}-[func]{}
/* Queue class based on linked list */
class LinkedListQueue {
private:
ListNode *front, *rear; // Front node front, back node rear
int queSize;
public:
LinkedListQueue() {
front = nullptr;
rear = nullptr;
queSize = 0;
}
~LinkedListQueue() {
// Traverse the linked list, remove nodes, free memory
freeMemoryLinkedList(front);
}
/* Get the length of the queue */
int size() {
return queSize;
}
/* Determine if the queue is empty */
bool isEmpty() {
return queSize == 0;
}
/* Enqueue */
void push(int num) {
// Add num behind the tail node
ListNode *node = new ListNode(num);
// If the queue is empty, make the head and tail nodes both point to that node
if (front == nullptr) {
front = node;
rear = node;
}
// If the queue is not empty, add that node behind the tail node
else {
rear->next = node;
rear = node;
}
queSize++;
}
/* Dequeue */
int pop() {
int num = peek();
// Remove head node
ListNode *tmp = front;
front = front->next;
// Free memory
delete tmp;
queSize--;
return num;
}
/* Access front element */
int peek() {
if (size() == 0)
throw out_of_range("Queue is empty");
return front->val;
}
/* Convert the linked list to Vector and return */
vector<int> toVector() {
ListNode *node = front;
vector<int> res(size());
for (int i = 0; i < res.size(); i++) {
res[i] = node->val;
node = node->next;
}
return res;
}
};
```
=== "Java"
@@ -638,7 +712,81 @@ In a circular array, `front` or `rear` needs to loop back to the start of the ar
=== "C++"
```cpp title="array_queue.cpp"
[class]{ArrayQueue}-[func]{}
/* Queue class based on circular array */
class ArrayQueue {
private:
int *nums; // Array for storing queue elements
int front; // Front pointer, pointing to the front element
int queSize; // Queue length
int queCapacity; // Queue capacity
public:
ArrayQueue(int capacity) {
// Initialize an array
nums = new int[capacity];
queCapacity = capacity;
front = queSize = 0;
}
~ArrayQueue() {
delete[] nums;
}
/* Get the capacity of the queue */
int capacity() {
return queCapacity;
}
/* Get the length of the queue */
int size() {
return queSize;
}
/* Determine if the queue is empty */
bool isEmpty() {
return size() == 0;
}
/* Enqueue */
void push(int num) {
if (queSize == queCapacity) {
cout << "Queue is full" << endl;
return;
}
// Calculate rear pointer, pointing to rear index + 1
// Use modulo operation to wrap the rear pointer from the end of the array back to the start
int rear = (front + queSize) % queCapacity;
// Add num to the rear
nums[rear] = num;
queSize++;
}
/* Dequeue */
int pop() {
int num = peek();
// Move front pointer one position backward, returning to the head of the array if it exceeds the tail
front = (front + 1) % queCapacity;
queSize--;
return num;
}
/* Access front element */
int peek() {
if (isEmpty())
throw out_of_range("Queue is empty");
return nums[front];
}
/* Convert array to Vector and return */
vector<int> toVector() {
// Only convert elements within valid length range
vector<int> arr(queSize);
for (int i = 0, j = front; i < queSize; i++, j++) {
arr[i] = nums[j % queCapacity];
}
return arr;
}
};
```
=== "Java"

View File

@@ -401,7 +401,70 @@ Below is an example code for implementing a stack based on a linked list:
=== "C++"
```cpp title="linkedlist_stack.cpp"
[class]{LinkedListStack}-[func]{}
/* Stack class based on linked list */
class LinkedListStack {
private:
ListNode *stackTop; // Use the head node as the top of the stack
int stkSize; // Length of the stack
public:
LinkedListStack() {
stackTop = nullptr;
stkSize = 0;
}
~LinkedListStack() {
// Traverse the linked list, remove nodes, free memory
freeMemoryLinkedList(stackTop);
}
/* Get the length of the stack */
int size() {
return stkSize;
}
/* Determine if the stack is empty */
bool isEmpty() {
return size() == 0;
}
/* Push */
void push(int num) {
ListNode *node = new ListNode(num);
node->next = stackTop;
stackTop = node;
stkSize++;
}
/* Pop */
int pop() {
int num = top();
ListNode *tmp = stackTop;
stackTop = stackTop->next;
// Free memory
delete tmp;
stkSize--;
return num;
}
/* Access stack top element */
int top() {
if (isEmpty())
throw out_of_range("Stack is empty");
return stackTop->val;
}
/* Convert the List to Array and return */
vector<int> toVector() {
ListNode *node = stackTop;
vector<int> res(size());
for (int i = res.size() - 1; i >= 0; i--) {
res[i] = node->val;
node = node->next;
}
return res;
}
};
```
=== "Java"
@@ -587,7 +650,46 @@ Since the elements to be pushed onto the stack may continuously increase, we can
=== "C++"
```cpp title="array_stack.cpp"
[class]{ArrayStack}-[func]{}
/* Stack class based on array */
class ArrayStack {
private:
vector<int> stack;
public:
/* Get the length of the stack */
int size() {
return stack.size();
}
/* Determine if the stack is empty */
bool isEmpty() {
return stack.size() == 0;
}
/* Push */
void push(int num) {
stack.push_back(num);
}
/* Pop */
int pop() {
int num = top();
stack.pop_back();
return num;
}
/* Access stack top element */
int top() {
if (isEmpty())
throw out_of_range("Stack is empty");
return stack.back();
}
/* Return Vector */
vector<int> toVector() {
return stack;
}
};
```
=== "Java"