fork(3) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct node {
  6. int data;
  7. struct node *next;
  8. };
  9.  
  10. void swap(struct node *a, struct node *b) {
  11. struct node tmp;
  12. memcpy(&tmp, a, sizeof(tmp));
  13. memcpy(a, b, sizeof(tmp));
  14. memcpy(b, &tmp, sizeof(tmp));
  15. }
  16.  
  17. void reverse(struct node *h) {
  18. if (!h || !h->next) {
  19. return;
  20. }
  21. struct node *tail = h->next;
  22. while (tail->next) {
  23. tail = tail->next;
  24. }
  25. swap(h, tail);
  26. struct node *p = NULL;
  27. struct node *c = tail;
  28. do {
  29. struct node *n = c->next;
  30. c->next = p;
  31. p = c;
  32. c = n;
  33. } while (c->next != tail);
  34. h->next = c;
  35. }
  36.  
  37. void print(struct node *p) {
  38. while (p) {
  39. printf("%d ", p->data);
  40. p = p->next;
  41. }
  42. printf("\n");
  43. }
  44.  
  45. int main(void) {
  46. struct node *head = malloc(sizeof(struct node));
  47. head->data = 1;
  48. head->next = malloc(sizeof(struct node));
  49. head->next->data = 2;
  50. head->next->next = malloc(sizeof(struct node));
  51. head->next->next->data = 3;
  52. head->next->next->next = NULL;
  53. print(head);
  54. reverse(head);
  55. printf("------\n");
  56. print(head);
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
1 2 3 
------
3 2 1