指针,栈和链表习题答案
2025-09-23 16:24:49
发布于:浙江
以下是3道习题的参考答案及详细解析:
习题1答案:指针基础
#include <iostream>
using namespace std;
int main() {
int num = 100;
int* ptr = #
cout << "修改前值: " << num << ", 地址: " << ptr << endl;
*ptr = 200; // 通过指针修改值
cout << "修改后值: " << num << ", 地址: " << ptr << endl;
return 0;
}
关键点:
&num获取变量地址
*ptr解引用修改值
指针地址在修改前后不变
习题2答案:栈实现字符串反转
#include <stack>
#include <string>
using namespace std;
string reverseString(const string& input) {
stack<char> charStack;
string result;
// 压栈
for(char c : input) {
charStack.push(c);
}
// 弹栈构建结果
while(!charStack.empty()) {
result += charStack.top();
charStack.pop();
}
return result;
}
执行过程示例:
输入 "hello":
- 栈状态(顶→底):o → l → l → e → h
- 弹出顺序:o → l → l → e → h
习题3答案:链表删除指定值
void deleteValues(Node* &head, int target) {
Node* curr = head;
Node* prev = nullptr;
while(curr != nullptr) {
if(curr->data == target) {
// 需要删除的节点
Node* temp = curr;
if(prev == nullptr) {
// 删除头节点
head = curr->next;
} else {
// 非头节点
prev->next = curr->next;
}
curr = curr->next;
delete temp;
} else {
// 保留的节点
prev = curr;
curr = curr->next;
}
}
}
删除逻辑图示:
删除值为2的节点:
原链表:1 → 2 → 3 → 2 → NULL
过程:
- 发现第一个2,修改1的next指向3
- 发现第二个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)
这里空空如也
有帮助,赞一个