题目5分析:(替换空格)
考虑到时间复杂度的问题,不能从前往后遍历,每遇到一个空格则后移之后所有的字符串;可根据一次遍历的空格数,从后往前一次后移所需要移动次数的字符串;
思路:
1.遍历获得空格数,原字符串长度
2.计算替换空格后的新字符串长度
3.以旧字符串的长度从后往前遍历,如果没有遇到空格则将原数组下标p1对应的元素复制到
新数组下标对应位置;如果遇到空格则插入字符串,p1向前移动一位;直到p1==p2结束遍历
#include <iostream> using namespace std; void replace_blank(char str[], int length) { if(str == nullptr||length <= 0)//空数组 return; int ori_length = 0, new_length = 0, blank=0; int i = 0; while (str[i] != '\0') { ++ori_length; if (str[i] == ' ') ++blank; ++i; } new_length = ori_length + 2 * blank; cout << "原数组长度:" << ori_length << "\n新数组长度:" << new_length << endl; int ori_index = ori_length, new_index = new_length; while(ori_index >= 0 && new_index > ori_index) { if (str[ori_index] == ' ') { str[new_index--] = '0'; str[new_index--] = '2'; str[new_index--] = '%'; } else str[new_index--] = str[ori_index]; --ori_index; } } void main() { int length = 30; char str[30] = { "we are champions." }; replace_blank(str, length); for (int i = 0; i < length; i++) cout << str[i] << " "; }
题目6分析:(从尾到头打印链表)
从前往后遍历链表,从后往前输出,可将此链表放入栈中,后入先出,同时删除后入结点;也可利用递归遍历结点,先遍历完之后在输出,此时因为递归的特性是从后往前输出的;
栈思路:
1.声明栈
2.遍历将链表放入栈中
3.遍历栈区,打印栈顶结点,然后删除此结点
递归思路:
1.从头指针开始,遍历链表
2.如果当前结点指向的下个结点不为空结点,则继续遍历
3.否则输出链表结点内容
#include <iostream> #include <stack> #include <time.h> using namespace std; //链表结点结构体类型 struct ListNode { int data; ListNode * next; }; //创建链表 void create_list(ListNode *head_ptr, int n) { for (int i = 1; i <= n; i++) { ListNode *new_node = new ListNode; new_node->data = i;//随机生成100以内的数字 new_node->next = head_ptr->next; head_ptr->next = new_node;//将结点插入到表头 } } //打印链表内容 void print_list(ListNode *head_ptr) { ListNode *node = head_ptr->next;//获得头节点 while (node != NULL) { cout << node->data << " "; node = node->next; } } void stack_reverse_cout_list(ListNode *head) { stack<ListNode *> nodes;//1.声明栈,用于存放链表 ListNode *node = head; while (node != nullptr)//2.遍历将链表放入栈中 { nodes.push(node); node = node->next; } while (!nodes.empty())//3.遍历栈区,打印栈顶结点,然后删除此结点 { node = nodes.top(); cout << node->data << endl; nodes.pop(); } } void reverse_cout_list(ListNode *head) { if (head != nullptr)//1.从头指针开始,遍历链表 { if (head->next != nullptr)//2.如果当前结点指向的下个结点不为空结点,则继续遍历 { reverse_cout_list(head->next); } cout << head->data << endl;//3.否则输出链表结点内容 } } void main() { ListNode *head_ptr=new ListNode; head_ptr->data = 0; head_ptr->next = NULL;//创建头指针 int n = 10; create_list(head, n); print_list(head); cout << "栈方法:" << endl; stack_reverse_cout_list(head); cout << "递归方法:" << endl; reverse_cout_list(head); }