C++单链表的创建和二叉树的创建
链表的创建
struct ListNode {
int val;
ListNode* next;
ListNode ( int x) : val ( x) , next ( NULL ) { }
} ;
ListNode* creat ( ) {
ListNode* head, * p;
int val[ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ;
head = new ListNode ( val[ 0 ] ) ;
p = head;
for ( int i = 1 ; i < 6 ; i++ ) {
ListNode* s = new ListNode ( val[ i] ) ;
p- > next = s;
p = s;
}
p- > next = NULL ;
return head;
}
二叉树的创建
#这是一个计算二叉树左叶子和与右叶子和之差
#include <iostream>
#include <string>
using namespace std;
struct BinaryTreeNode {
int val;
BinaryTreeNode* leftchild;
BinaryTreeNode* rightchild;
BinaryTreeNode ( int const & _val, BinaryTreeNode* _leftchild = NULL , BinaryTreeNode* _rightchild = NULL ) :
val ( _val) , leftchild ( _leftchild) , rightchild ( _rightchild) { }
} ;
int fun_L ( BinaryTreeNode* root) {
if ( root == NULL ) return 0 ;
int sum_l = 0 ;
if ( root- > leftchild != NULL && root- > leftchild- > leftchild == NULL && root- > leftchild- > rightchild == NULL ) sum_l + = root- > leftchild- > val;
return sum_l + fun_L ( root- > leftchild ) + fun_L ( root- > rightchild) ;
}
int fun_R ( BinaryTreeNode* root) {
if ( root == NULL ) return 0 ;
int sum_r = 0 ;
if ( root- > rightchild != NULL && root- > rightchild- > leftchild == NULL && root- > rightchild- > rightchild == NULL ) sum_r + = root- > rightchild- > val;
return sum_r + fun_R ( root- > leftchild) + fun_R ( root- > rightchild) ;
}
int main ( int argc, char * argv[ ] ) {
BinaryTreeNode* A = new BinaryTreeNode ( 1 ) ;
BinaryTreeNode* B = new BinaryTreeNode ( 2 ) ;
BinaryTreeNode* C = new BinaryTreeNode ( 4 ) ;
BinaryTreeNode* D = new BinaryTreeNode ( 7 ) ;
BinaryTreeNode* E = new BinaryTreeNode ( 3 ) ;
BinaryTreeNode* F = new BinaryTreeNode ( 5 ) ;
BinaryTreeNode* G = new BinaryTreeNode ( 6 ) ;
BinaryTreeNode* H = new BinaryTreeNode ( 8 ) ;
A- > leftchild = B;
A- > rightchild = E;
B- > leftchild = C;
C- > rightchild = D;
E- > leftchild = F;
E- > rightchild = G;
G- > leftchild = H;
int tol, tol_l , tol_r;
tol_l = fun_L ( A) ;
tol_r = fun_R ( A) ;
tol = tol_l - tol_r;
cout << tol << endl;
return 0 ;
}
map表的使用
#include <iostream>
#include <set>
#include <map>
#include <string>
using namespace std;
void print ( map< string, int > a) {
for ( auto x : a) {
cout << x. first << ":" << x. second << endl;
}
}
int main ( ) {
map< string, int > a;
a[ "1" ] = 10 ;
a[ "2" ] = 30 ;
a. erase ( "2" ) ;
a. insert ( pair< string, int > ( "4" , 40 ) ) ;
a. insert ( map< string, int > :: value_type ( "5" , 50 ) ) ;
print ( a) ;
cout << a. max_size ( ) << endl;
}
map表的函数
begin ( ) 返回指向map头部的迭代器
clear ( ) 删除所有元素
count ( ) 返回指定元素出现的次数
empty ( ) 如果map为空则返回true
end ( ) 返回指向map末尾的迭代器
equal_range ( ) 返回特殊条目的迭代器对
erase ( ) 删除一个元素
find ( ) 查找一个元素
get_allocator ( ) 返回map的配置器
insert ( ) 插入元素
key_comp ( ) 返回比较元素key的函数
lower_bound ( ) 返回键值>= 给定元素的第一个位置
max_size ( ) 返回可以容纳的最大元素个数
rbegin ( ) 返回一个指向map尾部的逆向迭代器
rend ( ) 返回一个指向map头部的逆向迭代器
size ( ) 返回map中元素的个数
swap ( ) 交换两个map
upper_bound ( ) 返回键值> 给定元素的第一个位置
value_comp ( ) 返回比较元素value的函数