【剑指offer】一些简单题05 06

剑指offer一些简单题

05 替换空格

题目

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

思考

  • 直接遍历,遇到空格就更改

代码

class Solution {
public:
    string replaceSpace(string s) {
        string ans = "";
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==' ')   ans+="%20";
            else    ans+=s[i];
        }
        return ans;
    }
};

06 从尾到头打印链表

题目

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

思考

  • 注意vector 有库函数reverse!!

代码

/**
 * 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) {
        vector<int> vec;
        while(head){
            vec.push_back(head->val);
            head = head->next;
        }
        reverse(vec.begin(),vec.end());
        return vec;
    }
};
原文地址:https://www.cnblogs.com/xuwanwei/p/14279104.html