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

@@ -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"