Question

Write an iterative and recursive version of a function to print out a linked list from head to tail and then do the same for printing a linked list from tail to head. Assume a singly linked list in all cases and access only to a head pointer at the time of the function call. struct node; typedef struct node Node; struct node int data; Node next;
C programming
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<stdio.h>

#include<stdlib.h>

/* Link list node */

struct Node

{

int data;

struct Node* next;

};

/* Function to reverse the linked list */

void tailToHead(struct Node* head)

{

// Base case

if (!head)

return;

// print the list after head node

tailToHead(head->next);

// After everything else is printed, print head

printf("%d ", head->data);

}

void headToTail(struct Node* head)

{

// Base case

if (!head)

return;

// After everything else is printed, print head

printf("%d ", head->data);

// print the list after head node

headToTail(head->next);

}

void iheadToTail(struct Node* head)

{

while (head!= NULL)

{

// print current data

printf("%d ", head->data);

// increase pointer

head=head->next;

}

}

/*UTILITY FUNCTIONS*/

/* Push a node to linked list. Note that this function

changes the head */

void push(struct Node** head_ref, char new_data)

{

/* allocate node */

struct Node* new_node =

(struct Node*) malloc(sizeof(struct Node));

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = (*head_ref);

/* move the head to pochar to the new node */

(*head_ref) = new_node;

}

/* Drier program to test above function*/

int main()

{

// Let us create linked list 10->20->30->40

struct Node* head = NULL;

push(&head, 40);

push(&head, 30);

push(&head, 20);

push(&head, 10);

printf("\nrecursive Head to tail \n");

headToTail(head);

printf("\n iterative Head to tail \n");

iheadToTail(head);

printf(" \n recursive Tail to Head \n");

tailToHead(head);

return 0;

}

Output:-

recursive Head to tail 
10 20 30 40 
 iterative Head to tail 
10 20 30 40  
 recursive Tail to Head 
40 30 20 10 
Add a comment
Know the answer?
Add Answer to:
C programming Write an iterative and recursive version of a function to print out a linked...
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