一、输入格式
- 输入数值和定长数组
cpp
int n;
cin>>n;
vector<int> nums(n);
for(int i=0;i<n;i++){
cin>>nums[i];
}
// 5
// 0 1 2 3 4
- 输入不定长数组
cpp
vector<int> nums;
int x;
while(cin>>x) nums.push_back(x);
// 1 2 3 4 5 6
- 输入字符串(以行为单位)
cpp
string s;
string p;
getline(cin,s); //读取一行字符串
getline(cin,p);
// abcdef
// asfdgh
- 输入字符串,根据空格划分子字符串
cpp
string input;
getline(cin,input);
istringstream iss(input); //输入字符串流(把字符串当作输入源来读)
string token;
vector<string> st;
while(iss>>token){ //从字符串流 iss 中读取一个单词(遇到空格自动停止),存到 token
st.push_back(token);
}
二、输出格式
- 输出数组(不能直接输出,必须按顺序遍历)
cpp
vector<int> nums = {1,2,3,4,5};
for(int i=0;i<nums.size();i++){
cout<<nums[i]<<" ";
}
// 输出:1 2 3 4 5
- 输出字符串
cpp
string s = "abcde";
cout<<s<<endl;
// 输出:abcde
三、链表构造
- 输入节点值数组
如:输入 1 2 4 5 6 8
cpp
#include<iostream>
#include<vector>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int val):val(val),next(nullptr){}
};
ListNode* buildList(vector<int>& nums){
if(nums.size()==0) return nullptr;
ListNode* head = new ListNode(nums[0]);
ListNode* cur = head;
for(int i=1;i<nums.size();i++){
ListNode* temp = new ListNode(nums[i]);
cur->next = temp;
cur = temp;
}
return head;
}
int main(){
vector<int> nums;
int x;
while(cin>>x) nums.push_back(x);
ListNode* head = buildList(nums);
return 0;
}
四、二叉树构造

- 输入完整层序遍历数组(空节点为-1,所有空节点都输入)
如:输入 1 -1 2 -1 -1 3
cpp
// 构造节点
struct Node{
Node* left;
Node* right;
int val;
Node(int v):val(v),left(nullptr),right(nullptr){}
};
// 构造二叉树
Node* buildTree(vector<int>& nums){
if(nums.size()==0 || nums[0]==-1) return nullptr;
vector<Node*> node(nums.size(),nullptr);
node[0] = new Node(nums[0]);
for(int i=1;i<nums.size();i++){
int p = (i-1)/2; //父节点下标为(i-1)/2
if(nums[i]!=-1 && node[p]!=nullptr){
//当本节点i不为空且父节点p不为空时,建立节点
node[i] = new Node(nums[i]);
//节点p的左节点2*p+1,节点p的右节点2*p+2
if(i==p*2+1) node[p]->left = node[i];
else node[p]->right = node[i];
}
}
return node[0];
}
int main(){
vector<int> nums;
int x;
while(cin>>x) nums.push_back(x);
Node* root = buildTree(nums);
return 0;
}
- 输入层序遍历字符串(空节点为"null")
如:输入 1 null 2 3
cpp
#include<iostream>
#include<vector>
#include<queue>
#include<sstream>
using namespace std;
// 构造节点
struct Node{
Node* left;
Node* right;
int val;
Node(int val):val(val),left(nullptr),right(nullptr){}
};
// 构造二叉树(层序遍历反推)
Node* buildTree(vector<string>& st){
if(st.size()==0 || st[0]=="null") return nullptr;
Node* head = new Node(stoi(st[0])); //构造头节点
queue<Node*> q; //队列
q.push(head);
int i=1;
while(i<st.size()){ //遍历每个数组元素,依次为队列中元素的左/右节点
Node* cur = q.front();
q.pop();
if(i<st.size() && st[i]!="null"){ //若不为null则建新节点,并加入队列
cur->left = new Node(stoi(st[i]));
q.push(cur->left);
}
i++;
if(i<st.size() && st[i]!="null"){
cur->right = new Node(stoi(st[i]));
q.push(cur->right);
}
i++;
}
return head;
}
int main(){
string input;
getline(cin,input);
istringstream iss(input);
string token;
vector<string> st;
while(iss>>token){
st.push_back(token);
}
Node* head = buildTree(st);
return 0;
}