1.字符串反转:
/**
给定一个字符串 str 请假字符串反转输出
示例:
给定 str = @"I am a programmer"
返回 str = @"remmargorp a ma I"
*/
+ (void)stringReverse{
char myStr[] = "I love my country";
char *left = myStr;
char *right = myStr + strlen(myStr) - 1;
while (left < right) {
char temp = *left;
*(left++) = *right;
*(right--) = temp;
}
NSLog(@"反转输出:%s",myStr);
}
运行:
2.单链表反转
+ (void)listReverse {
//定义结构体
struct Node *head = NULL;
struct Node *currentTail = NULL;
for (int i = 0; i < 10; i++) {
struct Node *node = malloc(sizeof(struct Node));
node->datas = i;
if (head == NULL) {
head = node;
}else {
currentTail->next = node;
}
currentTail = node;
}
//打印原结构体
struct Node *origiNode = head;
printf("原始结构体:");
while (origiNode != NULL) {
printf("%d",origiNode->datas);
origiNode = origiNode->next;
}
//开始反转
struct Node *moveNode = head;
struct Node *newNode = NULL;
while (moveNode != NULL) {
struct Node *tempNode = moveNode->next;
moveNode->next = newNode;
newNode = moveNode;
moveNode = tempNode;
}
//打印反转结构体
struct Node *reverseNode = newNode;
printf("\n反转结构体结构体");
while (reverseNode != NULL) {
printf("%d",reverseNode->datas);
reverseNode = reverseNode->next;
}
}
运行: