A simple and intuitive solution to the problem !! It might not be very efficient but it does certainly work.
node* swap(node *head)
{
node dummy;
node *prev, *curr, *u, *tmp;
if (head==NULL) return head;
prev=&dummy;
for(curr=head; curr!=NULL && curr->next!=NULL; ) {
u = curr->next;
tmp = u->next;
prev->next = u;
u->next = curr;
prev = curr;
curr = tmp;
}
prev->next = curr;
return dummy.next;
}
void print(const node *head)
{
for(const node *p=head; p; p=p->next)
printf("%d ", p->val);
putchar('\n');
}
node* swap(node *head)
{
node dummy;
node *prev, *curr, *u, *tmp;
if (head==NULL) return head;
prev=&dummy;
for(curr=head; curr!=NULL && curr->next!=NULL; ) {
u = curr->next;
tmp = u->next;
prev->next = u;
u->next = curr;
prev = curr;
curr = tmp;
}
prev->next = curr;
return dummy.next;
}
void print(const node *head)
{
for(const node *p=head; p; p=p->next)
printf("%d ", p->val);
putchar('\n');
}
No comments:
Post a Comment