程序逆序打印怎么编写代码

时间:2025-01-28 00:23:05 单机游戏

逆序打印程序可以通过多种方法实现,以下是几种常见的方法:

方法一:反向遍历字符串

```c

include

include

void ReversePrint(const char *s) {

int len = strlen(s);

for (int i = len - 1; i >= 0; i--) {

printf(" %c ", s[i]);

}

printf("\n");

}

int main() {

char a[] = "abcd";

ReversePrint(a);

getchar();

return 0;

}

```

方法二:先遍历到末尾,再遍历回来

```c

include

include

void ReversePrint(const char *s) {

const char *p = s;

while (*p) p++;

p--;

while (p >= s) {

printf(" %c ", *p);

p--;

}

printf("\n");

}

int main() {

char a[] = "abcd";

ReversePrint(a);

getchar();

return 0;

}

```

方法三:递归遍历

```c

include

include

void ReversePrint(const char *s, int len) {

if (len == 0) {

return;

}

printf("%c", s[len - 1]);

ReversePrint(s, len - 1);

}

int main() {

char a[] = "abcd";

ReversePrint(a, strlen(a));

printf("\n");

getchar();

return 0;

}

```

方法四:逆序打印一维数组

```c

include

void ReversePrintArray(int arr[], int size) {

for (int i = size - 1; i >= 0; i--) {

printf("%d ", arr[i]);

}

printf("\n");

}

int main() {

int a[] = {1, 5, 4, 8, 6, 4};

ReversePrintArray(a, sizeof(a) / sizeof(a));

return 0;

}

```

方法五:逆序打印数字

```c

include

void ReversePrintNumber(int n) {

int temp = 0;

while (n > 0) {

temp = temp * 10 + n % 10;

n /= 10;

}

printf("%d\n", temp);

}

int main() {

int n;

printf("请输入一个数字: ");

scanf("%d", &n);

ReversePrintNumber(n);

return 0;

}

```

方法六:逆序打印链表

```c

include

struct Node {

int data;

struct Node* next;

};

void ReversePrintList(struct Node* head) {

if (head == NULL) {

return;

}

ReversePrintList(head->next);

printf("%d ", head->data);

}

int main() {

// 创建链表并初始化

struct Node* head = NULL;

// 添加节点到链表

// ...

ReversePrintList(head);

return 0;

}

```

这些方法涵盖了字符串、数组和链表的逆序打印。根据具体需求选择合适的方法即可。