6-2 reverse data to establish the list (20 points)

This problem required to achieve a function, a list in reverse order of the input data.

Function interface definition:
struct ListNode createList * ();

Createlist function scanf acquired using input from a series of positive integers, it indicates the end of input when read -1. Establishing a list in reverse order of the input data, and return the list head pointer. List node structure is defined as follows:

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

Referee test sample program:
#include <stdio.h>
#include <stdlib.h>

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

struct ListNode *createlist();

int main()
{
struct ListNode *p, *head = NULL;

head = createlist();
for ( p = head; p != NULL; p = p->next )
    printf("%d ", p->data);
printf("\n");

return 0;

}

/ * Your code will be embedded here * /

Sample input:
1234567-1

Output Sample:
7654321

struct ListNode *createlist()
{
    struct ListNode *L=(struct ListNode*)malloc(sizeof(struct ListNode));
    L->next=NULL;
    int e;
    scanf("%d",&e);
    while(e!=-1)
    {
        struct ListNode *s=(struct ListNode*)malloc(sizeof(struct ListNode));
        s->next=NULL;
        s->data=e;
        s->next=L->next;
        L->next=s;
        scanf("%d",&e);
    }
    return L->next;//如果直接返回L的话,就会带有头结点,打印出来的数中会带有头结点中的随机值。这样打印出来就是从首元开始的了
}
Published 33 original articles · won praise 4 · Views 3053

Guess you like

Origin blog.csdn.net/qq_45728926/article/details/105168053