14836 - Reverse output of linked sequence data   

Description

Implement the function print_list_backward to print the data in a linked list in reverse order.
First, the header file for the linked list is defined below.

linked-list.h

struct listnode {
    int data;
    struct listnode *next;
};
typedef struct listnode ListNode;

The main program and sample input/output are shown below.
Please implement the function print_list_backward.
Note that although the numbers are input from small to large, the method used in the main program inserts new numbers at the front of the list.
Therefore, the final list is stored in reverse order, so the result of reverse printing should appear from small to large.

print-list-backward-main.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "linked-list.h"
void print_list_backward(ListNode *ptr);
int main(void)
{
    int n;
    ListNode *head;
    ListNode *previous = NULL;
    while (scanf("%d", &n) != EOF) {
        head = (ListNode*)malloc(sizeof(ListNode));
        assert(head != NULL);
        head->data = n;
        head->next = previous;
        previous = head;
    }
    print_list_backward(head);
    return 0;
}

 

Input

Several integers, one per line. Ends at EOF.

The main program inserts each integer at the head → list is reversed.

You should print the linked list backward, so output is from smallest to largest.

Ex. 1
2
3
4
5
6
7

Output

Each number printed on its own line.

Ex. 1
2
3
4
5
6
7
 

Sample Input  Download

Sample Output  Download




Discuss