Question

If If you have a normal singly linked list, how could you print the items backward?

If If you have a normal singly linked list, how could you print the items backward?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Print items Backwards in a Normal Singly Linked List-

Given a linked list, can print its items backwards using a recursive function. For example, if tthe given linked list is

1->2->3->4 , then output should be4->3->2->1.

Algorithm-

1.Call print reverse for hed->next.

2. Print head ->data

Implementation:

   #include <stdio.h> #include<stdlib.h> struct node{ int data; struct node*next; }; struct node *head = NULL; struct node *current = NULL; void reverse_print(struct node *list){ if(list == NULL){ printf("[null] => "); return; } reverse_print (list->next); printf(" %d =>",list ->data); } //create linked list void insert (int data){ //allocate memory for new node; struct node *link = (struct node*) malloc(sizeof(struct node)); link-> data = data; link-> next = NULL; // if head is empty , create new list if (head == NULL) { head = link ; return; } current = head //move to the end of the list while (current ->next! = NULL) current = current ->next; // Insert to the end of the list current ->next = link; } int main (){ insert(10); insert(20); insert(30); insert(1); insert(40); insert(56); reverse_print(head); return 0; } 

OUTPUT:

Output of the program should be

[null] => 56 => 40 => 1 => 30 => 20 => 10 =>

Add a comment
Know the answer?
Add Answer to:
If If you have a normal singly linked list, how could you print the items backward?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT