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
What is the most common mistake on c++ and oo projects?
How do you invoke a base member function from a derived class in which you have not overridden that function?
How many types of scopes are there in c++?
Discuss the effects occur, after an exception thrown by a member function is unspecified by an exception specification?
What is the header file for setw?
What is a hashmap c++?
What is the use of class in c++?
Why do we need pointers?
What are pointer-to-members? Explain.
What is the use of typedef?
What is bubble sort c++?
What are exceptions c++?
What is the latest c++ version?
How the programmer of a class should decide whether to declare member function or a friend function?
Should the member functions which are made public in the base class be hidden?