以下是3道习题的参考答案及详细解析:
习题1答案:指针基础
#include <iostream>
using namespace std;
int main() {
int num = 100;
int* ptr = #
}
关键点:
&num获取变量地址
*ptr解引用修改值
指针地址在修改前后不变
习题2答案:栈实现字符串反转
#include <stack>
#include <string>
using namespace std;
string reverseString(const string& input) {
stack<char> charStack;
string result;
}
执行过程示例:
输入 "hello":
1. 栈状态(顶→底):o → l → l → e → h
2. 弹出顺序:o → l → l → e → h
习题3答案:链表删除指定值
void deleteValues(Node* &head, int target) {
Node* curr = head;
Node* prev = nullptr;
}
删除逻辑图示:
删除值为2的节点:
原链表:1 → 2 → 3 → 2 → NULL
过程:
1. 发现第一个2,修改1的next指向3
2. 发现第二个2,修改3的next指向NULL
最终:1 → 3 → NULL
附加思考题解析
双向链表实现栈的优化方案:
struct StackNode {
int data;
StackNode *prev, *next;
};
class LinkedListStack {
StackNode *top, *bottom; // 新增bottom指针
public:
// push/pop操作仍只需操作top
int getBottom() { return bottom->data; } // O(1)获取栈底
};
优势:
保持栈的LIFO特性
栈底访问时间复杂度从O(n)降到O(1)