带头结点单链表的就地倒置

reverse部分的节点是怎样变化的?


#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    struct Node *next;
};
const int sizeN=sizeof(struct Node);
void output(struct Node*head){
    while(head=head->next)
        printf("%d    ",head->data);
    printf("\n");
}
struct Node *reverse(struct Node*head){
    struct Node *p=head->next,*q=p->next;
    free(head);
    p->next=NULL;
    while(head=q->next){
        q->next=p;
        p=q;
        q=head;
    }
    q->next=p;
    head=malloc(sizeN);
    head->next=q;
    return head;
}
int main(){
    struct Node *head=malloc(sizeN),
        *p=head,*q;
    head->next=p;
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        q->data=n;
        q->next=NULL;
        p=p->next=q;
        q=malloc(sizeN);
    }
    p->next=NULL;
    free(q);
    output(head);
    head=reverse(head);
    output(head);
    return 0;
}

修改如下,见注释,供参考:

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    struct Node *next;
};
const int sizeN=sizeof(struct Node);
void output(struct Node*head){
    while(head=head->next)
        printf("%d    ",head->data);
    printf("\n");
}
void  reverse(struct Node*head){  //struct Node *reverse(struct Node*head){//修改
    struct Node *p=head->next,*q=NULL; //struct Node *p=head->next,*q=p->next;//修改
                                       //free(head);  //修改
    head->next = NULL;                //p->next=NULL; //修改
    while(p){
        q = p;
        p = p->next;   //q->next=p;   //修改
        q->next = head->next;//p=q;   //修改
        head->next = q; //q=head;     //修改
    }
                       //q->next=p;    //修改
                       //head=(struct Node*)malloc(sizeN);
                        //head->next=q;
                        //return head;
}
int main(){
    struct Node *head=(struct Node*)malloc(sizeN);// ,修改
    struct Node *p=head,*q;   //修改
    head->next=NULL;  //head->next=p; 修改
    int t;
    scanf("%d",&t);
    while(t--){
                      //int n;   //修改
        q=(struct Node*)malloc(sizeN);//修改
        q->next=NULL;
        scanf("%d",&q->data);      //修改
                      //q->data=n; //修改
        p->next=q;     //修改
        p = q;         //修改
    }
    p->next=NULL;
                       //free(q); //修改
    output(head);

    reverse(head);    //修改
    output(head);
    
    return 0;
}