Leetcode_从尾到头打印链表&替换空格

替换空格

题目要求

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

分析

最简单的思路是用string容器来做,涉及到字符串的查找和替换

 代码实现

 1 class Solution {
 2 public:
 3     string replaceSpace(string s) {
 4         int pos = s.find(" ");
 5     while(pos!=-1)
 6     {
 7      s.replace(pos,1,"%20");
 8      pos = s.find(" ");
 9     }
10     cout<<s<<endl;
11     return s;
12     }
13 };

从尾到头打印链表

题目要求

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

分析

一开始想到的是反转链表,但是换一个思路可以将结果数组反转过来岂不是更简单,所以为了简化代码,我是用的动态数组vector容器来做,反转只需要用<algorthm>中的reverse()反转vector容器即可

代码实现

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     vector<int> reversePrint(ListNode* head) {
12         ListNode* p = head;
13         vector<int> a;
14         while(p)
15         {
16             a.push_back(p->val);  //个体vector容器赋值
17             p=p->next;
18         }
19         //用<algorthm>中的reverse()反转vector容器
20         reverse(a.begin(),a.end());
21         return a;
22     }
23 };
原文地址:https://www.cnblogs.com/g414056667/p/13817260.html