Reversing a linked list
#include <stdio.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node* reverse (Node* head) {
Node* previous=NULL;
Node* current=head;
Node* follow=head->next;
Node* tmp;
if (head == NULL || follow == NULL)
return head;
while (follow->next != NULL) {
tmp=follow;
follow=follow->next;
tmp->next=current;
current->next=previous;
previous=current;
current=tmp;
}
follow->next=current;
current->next=previous;
return follow;
}
void printlist (Node* node) {
if (node==NULL)
return;
printf ("%d ",node->val);
printlist (node->next);
}
int main (int argc, char* argv[]) {
Node a,b,c,d;
Node *t;
a.val=1;
a.next=&b;
b.val=2;
b.next=&c;
c.val=3;
c.next=&d;
d.val=4;
d.next=NULL;
printlist(&a);
printlist(t);
printf ("\n");
return 0;
}