Write a program to reverse a linked list?

Answer Posted / murali

/* Error Checking is not done */

#include <stdio.h>
typedef struct node {
char ch;
struct node *next;
} list;
list* addNode(const list *start, char ch) {
list *ll;
ll = (list *)start;
while( ll->next != NULL ) { ll = ll->next; }
ll->next = (list *) malloc(sizeof(list));
ll->next->ch = ch;
ll->next->next = NULL;
return ll->next;
}
void printList(const list *start) {
list *ll;
ll = (list *)start;
while ( ll->next != NULL ) {
printf(" %c --> ", ll->ch );
ll = ll->next;
}
printf(" %c --> ", ll->ch );
printf( " NULL ");
}
void reverse(list *a, list *b) {
if( b->next != NULL )
reverse(b, b->next);
b->next = a;
a->next = NULL;
}
int main() {

list *end;
list *start = (list *) malloc(sizeof(list));
start->ch = 'A';
start->next = NULL;

addNode(start, 'B');
addNode(start, 'C');
addNode(start, 'D');
addNode(start, 'E');
end = addNode(start, 'F');

printList(start);
printf("\n");

reverse(start, start->next);

printList(end);
printf("\n");

return 0;
}

Is This Answer Correct ?    9 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

By using c++ with an example describe linked list?

596


What is the difference between interpreters and compilers?

624


what is c++

1793


Is c++ the most powerful language?

560


What is the benefit of c++?

589






Define copy constructor.

617


How many types of comments are there in c++?

570


What are the general quetions are in DEna bank manager IT/System interviews?

1531


What is the limitation of cin while taking input for character array?

1444


How do you save a c++ program?

549


What does catch(…) mean?

608


Is c++ slower than c?

569


Write about the members that a derived class can add?

563


What is the difference between the functions memmove() and memcpy()?

621


What is c++ w3school?

622