c语言-复制字符串3种方法(类似strcpy()函数)

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

//方法一
void MyStrcpy1(char* s1, char* s2)
{
	while (*s2 != '\0')
	{
		*s1++ = *s2++;
	}
	*s1 = *s2;  //或者将该行改为:   *s1 = '\0';
}

//方法二
void MyStrcpy2(char* s3, char* s4)
{
	while (*s3++ = *s4++);
}

//方法三
char* MyStrcpy3(char* s5, const char* s6)
{
	char* ret = s5;  //存储首元素地址
	while (*s5++ = *s6++);
	return ret;  //返回解引用后的首元素地址
}

int main()
{
	char str1[] = "************";
	char str2[] = "welcome";
	char str3[] = "************";
	char str4[] = "thank you";
	char str5[] = "************";
	char str6[] = "hello";

	MyStrcpy1(str1, str2);
	MyStrcpy2(str3, str4);
	
	printf("%s\n",str1);
	printf("%s\n",str3);
	printf("%s\n", MyStrcpy3(str5, str6));
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
复制二叉树可以采用递归的方式,对每个节点进行复制,并递归复制其左右子树。以下是一个用 C 语言实现的例子: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树结构体 typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 复制二叉树 TreeNode* copyTree(TreeNode* root) { if (root == NULL) { return NULL; } TreeNode* new_root = (TreeNode*)malloc(sizeof(TreeNode)); new_root->val = root->val; new_root->left = copyTree(root->left); new_root->right = copyTree(root->right); return new_root; } // 中序遍历二叉树 void inorderTraversal(TreeNode* root) { if (root == NULL) { return; } inorderTraversal(root->left); printf("%d ", root->val); inorderTraversal(root->right); } int main() { // 创建二叉树 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = 1; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 2; root->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->val = 3; root->left->left = NULL; root->left->right = NULL; root->right->left = (TreeNode*)malloc(sizeof(TreeNode)); root->right->left->val = 4; root->right->right = NULL; root->right->left->left = NULL; root->right->left->right = NULL; // 复制二叉树 TreeNode* new_root = copyTree(root); // 中序遍历原二叉树和复制后的二叉树 printf("Original tree: "); inorderTraversal(root); printf("\n"); printf("Copied tree: "); inorderTraversal(new_root); printf("\n"); return 0; } ``` 输出结果为: ``` Original tree: 2 1 4 3 Copied tree: 2 1 4 3 ``` 可以看到,复制后的二叉树与原二叉树结构相同,并且输出的中序遍历结果也相同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值