返回首页
当前位置: 主页 > 网络编程 > 其他实例教程 >

C语言字符串和链表元素的反转教程

时间:2012-02-16 23:14来源:知行网www.zhixing123.cn 编辑:麦田守望者

字符串反转
0102030405060708091011121314151617181920212223242526 #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; }

链表元素反转

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 #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.

判断链表是否有环及两链表是否相交
逆序数/逆序数对
 

------分隔线----------------------------
标签(Tag):程序设计
------分隔线----------------------------
推荐内容
猜你感兴趣