Home > front end >  C: Print Reverse Linked List
C: Print Reverse Linked List

Time:03-19

I'm struggling with what might seem a very simple question about linked lists in C. Here it goes:

I need to print a reverse linked list with a space between elements. After printing the last (in this case, first) element I have to break page instead of printing a space. So it would be something as the following:

Linked List: [1,2,3,4]
Expected Output: 4 3 2 1\n

I am aware that I have to store information from the first element in order to create a conditional structure to implement what the question asks. However, since I'm using recursion I've got no clue how.

Here's the state of my current function:

void print_list(LinkedNode *start)
    if(start == NULL){
        return;
    }
    
    print_list(start->next);
    printf("%d ", start->data);
    return;

And here's the struct of the list:

typedef struct LinkedNode LinkedNode;
struct LinkedNode {
   int data;
   LinkedNode *next;
};

Also note that I cannot use any header besides stdio.h and stdlib.h.

I almost forgot to mention but this is my first question here so I would really appreciate any tips around.

Thanks in advance!

CodePudding user response:

This is a very simple method if you want to end with \n, not " \n". There are probably better methods, but I just wanted a quick solution:

void print_list(LinkedNode *start, char delim)
{
    if(start == NULL){
        return;
    }
    
    print_list(start->next, ' ');
    printf("%d%c", start->data, delim);
    return;
}

int main(int argc, char** argv)
{
    // initialize my_list
    print_list(my_list, '\n');
}

CodePudding user response:

Figured it out!

Thanks to @Afshin and @WhozCraig!

Solution down below:

void print_aux(LinkedNode *start, int aux){
    if(start == NULL){
        return;
    }

    aux  ;
    print_aux(start->next, aux);
    aux--;
    if(aux!=0) printf("%d ", start->data);
    else printf("%d", start->data);
    return;
}

void print_list(LinkedNode *start){
    print_aux(start, 0);
    printf("\n");
}
  • Related