Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I would like to print a linked list in reverse using a recursive void function.

ID: 3887774 • Letter: I

Question

I would like to print a linked list in reverse using a recursive void function. Here is what i have so far.

int lst_print_rev(LIST *l) {

  

if (l->front->next == NULL)

return 0;

else {

LIST *temp = l;

temp->front = temp->front->next;

temp->back = temp->back;

  

lst_print_rev(temp);

  

printf(FORMAT, temp->front->val);

}

  

  

return 0;

}

typedef struct node {

ElemType val;

struct node *next;

struct node *back;

  

} NODE;

struct list_struct {

NODE *front;

NODE *back;

int size;

};

LIST *lst_create() {

LIST *l = malloc(sizeof(LIST));

  

l->front = NULL;

l->back = NULL;

l->size = NULL;

return l;

}

void lst_push_front(LIST *l, ElemType val) {

NODE *p = malloc(sizeof(NODE));

  

p->val = val;

p->next = l->front;

l->size++;

  

l->front = p;

if(l->back == NULL) // was empty, now one elem

l->back = p;

  

}

void lst_push_back(LIST *l, ElemType val) {

NODE *p;

  

if(l->back == NULL) // list empty - same as push_front

lst_push_front(l, val);

else { // at least one element before push

p = malloc(sizeof(NODE));

p->val = val;

l->size++;

  

p->next = NULL;

l->back->next = p;

  

l->back = p;

}

}

Explanation / Answer

    // print the list after head node

    printReverse(head->next);

    // After everything else is printed, print head

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

}

  

/*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 1->2->3->4

    struct Node* head = NULL;   

    push(&head, 4);

    push(&head, 3);

    push(&head, 2);

    push(&head, 1);

   

    printReverse(head);

    return 0;

}