Guest

reverse_linked_list

By: a guest on Aug 14th, 2010  |  syntax: C  |  size: 1.25 KB  |  hits: 50  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node {
  5.         struct node *next;
  6.         char data;
  7. };
  8.  
  9.  
  10. // The last node must have n->next == NULL
  11. struct node *reverse_list(struct node *current, struct node *last) {
  12.         struct node *next = current->next;
  13.         current->next = last;
  14.         if (next != NULL) {
  15.                 return reverse_list(next, current);
  16.         } else {
  17.                 return current;
  18.         }
  19. }
  20.  
  21. struct node *reverse_list2(struct node *top) {
  22.         struct node *next, *last = top, *first = top;
  23.         while (top->next != NULL) {
  24.                 next = top->next;
  25.                 top->next = last;
  26.                 last = top;
  27.                 top = next;
  28.         }
  29.         top->next = last;
  30.         first->next = NULL;
  31.         return top;
  32. }
  33.  
  34. int main(int argc, char **argv) {
  35.         char i;
  36.         struct node *top, *current;
  37.         current = top = malloc(sizeof(struct node));
  38.         current->data = 'a';
  39.         for (i = 'b'; i <= 'z'; i++) {
  40.                 current->next = malloc(sizeof(struct node));
  41.                 current = current->next;
  42.                 current->data = i;
  43.         }
  44.         struct node *reversed = reverse_list(top, NULL);
  45.         struct node *r = reversed;
  46.         // print
  47.         while (reversed != NULL) {
  48.                 printf("%c", reversed->data);
  49.                 reversed = reversed->next;
  50.         }
  51.         printf("\n");
  52.         reversed = reverse_list2(r);
  53.         // print
  54.         while (reversed != NULL) {
  55.                 printf("%c", reversed->data);
  56.                 reversed = reversed->next;
  57.         }
  58.         printf("\n");
  59. }