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;
}
3 Comments:
wow, your weblog is sooooo difficult to understand! maybe I am not a IT student, seems so complex!
maybe you are the only one who understand yourself.
Well, these are common interview questions given by microsoft, google, etc... for the software engineers position.
You are missing the following line in between printlist()
t = reverse(&a);
I'm having a google interview tomorrow and I was counting on you. Hopefully there are no more mistakes :-P
/a
Post a Comment
<< Home