【C】字符串和链表元素的反转
比较简单的C语言笔试题,自己写了一下,记录
字符串反转
#include <stdio.h> char *reverse(char *str) { int len = strlen(str); int steps = len / 2; int i, j; for(i=0; i< steps; i++) { j = len - 1 - i; str[i] = str[j] ^ str[i]; str[j] = str[j] ^ str[i]; str[i] = str[j] ^ str[i]; } return str; } int main(int argc, char *argv[]) { char s[] = "abcdef!"; printf("%s\n", s); reverse(s); printf("%s\n", s); return 0; }
链表元素反转
#include <stdio.h> typedef struct node { struct node *next; int val; } Node; Node *create(int n) { Node *head = NULL, *p = NULL, *cur=NULL; while(n--) { p = (Node*)malloc(sizeof(Node)); p->val = n; p->next = NULL; if (head == NULL) { cur = head = p; } else { cur->next = p; cur = p; } } return head; } void print(Node *head) { Node *p = head; while(p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); } Node *reverse(Node *head) { Node *cur, *q, *p = head; if (p == NULL || p->next == NULL) { return p; } else { q = p->next; cur = reverse(p->next); q->next = p; p->next = NULL; return cur; } } int main(int argc, char *argv[]) { Node *head = create(10); print(head); head = reverse(head); print(head); return 0; }
P.S.
标签: C
还没有人抢沙发呢~