数据结构刷题(一)
正儿八经刷题第一天
1.替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例1
输入:s = "We are happy."
输出:"We%20are%20happy."
class Solution {
public:
string replaceSpace(string s) {
string n;
for(int i=0;i<s.length();i++){
if(s[i]==' ') {n = n+"%20";}
else n = n+s[i];
}
return n;
}
};
2.从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int>stk;
vector<int>ans;
while(head!=nullptr)
{
stk.push(head->val);
head=head->next;
}
while(!stk.empty())
{
ans.push_back(stk.top());
stk.pop();
}
return ans;
}
};
Note:
一样的思想,自己写的总报错,估计是++、–内存的问题,不能调试,搞了半天,最后还是用了栈,本来想用数组的,有空回头把这个再写了。