Creation and inversion of a singly linked list with no head

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

Node* CreateList(void)
{
    int val,i,n;
    Node *head,*p,*q;

    head = NULL;
    printf("Please enter the length of the linked list you want to create:\n");
    scanf("%d",&n);
    printf("Please enter the data you want to enter:\n");

    for(i=0; i<n; i++)
    {
        scanf("%d",&val);
        p = (Node*)malloc(sizeof(Node));
        p->data = val;

        if(head == NULL)
        {
            head=q=p;
        }
        else
            q->next = p;
        q=p
    }
    q->next = NULL;
    return head;
}

void showlist(Node* head)
{
    Node * p;
    p=head;
    while(p)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

// reverse the linked list
Node* ReverseList(Node* head)
{
    Node* p,*q,*r;
    p=head;
    q=r=NULL;

    while(p)
    {
        q = p->next; //q stores the pointer to the next node of p
        p->next = r; //p points to r
        r = p;
        p = q
    }
    return r;
}

intmain()
{
    Node *head;
    head = CreateList();
    showlist(head);

    head = ReverseList(head);
     showlist(head);
    //printf("HelloWorld!\n");
    return 0;
}

running result:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325476031&siteId=291194637