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

How can I learn dev c++ programming?

761


What's the order in which the local objects are destructed?

1005


What is pointer with example?

732


how can i access a direct (absolute, not the offset) memory address? here is what i tried: wrote a program that ask's for an address from the user, creates a FAR pointer to that adress and shows it. then the user can increment/decrement the value in that address by pressing p(inc+) and m(dec-). NOW, i compiled that program and opened it twice (in 2 different windows) and gave twice the same address to it. now look what happen - if i change the value in one "window" of the program, it DOES NOT change in the other! even if they point to the same address in the memory! here is the code snippet: //------------------------------------------------------ #include //INCLUDE EVERY KNOWN HEADER FILE #include //FOR ANY CASE... #include #include #include main() { int far *ptr; //FAR POINTER!!! long address; char key=0; //A KEY FROM THE KEYBOARD int temp=0; clrscr(); cout<<"Enter Address:"; cin>>hex>>address; //GETS THE ADDRESS clrscr(); (long)ptr=address; temp=*ptr; //PUTS THE ADDRESS IN THE PTR cout<<"["<

2068


What is the main function c++?

812


When can I use a forward declaration?

798


why is iostream::eof inside a loop condition considered wrong?

807


What are c++ manipulators?

801


Ask to write virtual base class code?

2449


Explain the scope of resolution operator.

832


What is the prototype of printf function?

856


When to use “const” reference arguments in a function?

789


Define pre-condition and post-condition to a member function in c++?

875


What is the difference between the indirection operator and the address of oper-ator?

813


List the advantages of inheritance.

864