- 从尾到头打印链表
方法一:递归法
/**
* 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) {
fun(head);
return res;
}
private:
vector<int> res;
void fun(ListNode* head)
{
if(head == nullptr)
{
return;
}
else
{
fun(head->next);
res.push_back(head->val);
}
}
};
方法二:辅助栈法
/**
* 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> s;
vector<int> v;
while(head)
{
s.push(head->val);
head = head->next;
}
while(!s.empty())
{
v.push_back(s.top());
s.pop();
}
return v;
}
};
依据题意,该链表是个单向链表只有next指针,所以只能从前往后遍历。想要达到从后往前的效果可以利用辅助栈法和递归的思想
- 替换空格
class Solution {
public:
string replaceSpace(string s) {
int count = 0, length = s.size();
for(int i = 0; i < length; i++)
{
if(s[i] == ' ')
{
count++;
}
}
s.resize(length + 2*count);
for(int i = length-1, j = s.size()-1; i < j; i--, j--)
{
if(s[i] != ' ')
{
s[j] = s[i];
}
else
{
s[j-2] = '%';
s[j-1] = '2';
s[j] = '0';
j -=2;
}
}
return s;
}
};
思路在:新字符串长度 = 原字符串长度 + 2 * 空格个数,然后从后往前遍历填好新数组的空,并且这里需要两个游标变量i和j