如何在 C 语言中实现换位输出207


在 C 语言中,换位输出是一种将数字或字符序列中的各个元素以相反顺序排列的过程。此技术可用于反转字符串、整数或链表等数据结构。

反转字符串

以下是反转字符串的 C 语言代码示例:```c
#include
#include
int main()
{
char str[] = "GeeksforGeeks";
int len = strlen(str);
for (int i = 0; i < len / 2; i++)
{
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
printf("Reversed string: %s", str);
return 0;
}
```

反转整数

以下是反转整数的 C 语言代码示例:```c
#include
int main()
{
int num = 12345;
int reversed_num = 0;
while (num != 0)
{
reversed_num = reversed_num * 10 + num % 10;
num /= 10;
}
printf("Reversed number: %d", reversed_num);
return 0;
}
```

反转链表

以下是反转链表的 C 语言代码示例:```c
#include
#include
struct Node
{
int data;
struct Node *next;
};
struct Node *reverse_list(struct Node *head)
{
struct Node *current = head;
struct Node *prev = NULL;
struct Node *next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
int main()
{
struct Node *head = (struct Node *)malloc(sizeof(struct Node));
head->data = 1;
head->next = (struct Node *)malloc(sizeof(struct Node));
head->next->data = 2;
head->next->next = (struct Node *)malloc(sizeof(struct Node));
head->next->next->data = 3;
head->next->next->next = (struct Node *)malloc(sizeof(struct Node));
head->next->next->next->data = 4;
head->next->next->next->next = NULL;
struct Node *reversed_head = reverse_list(head);
while (reversed_head != NULL)
{
printf("%d ", reversed_head->data);
reversed_head = reversed_head->next;
}
return 0;
}
```

注意:对于简单的反转操作,可以使用额外的存储空间(例如数组或栈)。
对于链表等更复杂的数据结构,建议使用递归或迭代方法进行就地反转。
反转算法的效率取决于数据的类型和大小。

2025-01-25


上一篇:理解 C 语言中的函数参数

下一篇:C 语言函数调用宝塔星阵