Print a singly linked list in reverse order

Well, that was a bonus question in the CMPS 280 test in southeast Louisiana. Print a single list in reverse in three lines. Any ideas?

+4
source share
4 answers

C fulfilling your bonus question in three lines:

#include <stdio.h>

struct node {
    int data;
    struct node* next;
};

void ReversePrint(struct node* head) {
    if(head == NULL) return;
    ReversePrint(head->next);
    printf("%d ", head->data);
}

int main()
{
    struct node first;
    struct node second;
    struct node third;

    first.data = 1;
    second.data = 2;
    third.data = 3;

    first.next = &second;
    second.next = &third;

    ReversePrint(&first); // Should print: 3 2 1
    printf("\n");

    return 0;
}
+17
source

If you are allowed to use a different data structure, use the stack.

Step 1: Move the linked list from the head of the node and push the key onto the stack until you reach the last node. It takes O (n) time.

Step 2: pull items from the stack. It will take O (1) time.

Consequently, the code will be

while(head != null){
stack.push(head.val);
head = head.next;
}
while(stack.isEmpty() != true){
stack.pop();
}
+3

, SO . , , , , , , .

SO

, , :), , :

reversePrint(head)
    if head is null then return // Line 1: base case
    reversePrint(head.next)     // Line 2: print the list after head
    print(head.data)            // Line 3: print head
+2

All Articles