Segment errors that cannot be solved by inverted rookies in C language linked list

topic description

list inversion
this problem requires the implementation of a function that inverts a given one-way linked list, that is, the header is set to the footer and the footer is set to the footer. List nodes are defined as follows

struct ListNode {

int data;
struct ListNode *next;

}

sources of topics and their own ideas

topic source
https://pintia.cn/problem-set.
the method I use is headless (this linked list should have no header node)

related codes

/ / Please paste the code text below (do not replace the code with pictures)

this is my own answer
struct ListNode reverse (struct ListNode head)
{

struct ListNode *p, *q;
p = head->next;
head->next = NULL;
while (p != NULL)
{
    q = p;
    p = p->next;
    q->next = head;
    head = q;
}
return head;

}

what result do you expect? What is the error message actually seen?

all the codes found by Baidu seem to be head inserts with header nodes. I also think it"s no problem when I draw several situations on draft paper, but I really don"t have a clue. I hope God will give me a little bit of advice. Thank you

C
Aug.15,2021

//
static NODE *reverseList(NODE *pHead)
{
    NODE *p;
    NODE *newHead;

    if(pHead == NULL || pHead->next == NULL)
    {
        return pHead;
    }
    p = pHead->next;
    newHead = reverseList(p);
    p->next = pHead;
    pHead->next = NULL;

    return newHead;
}

//
static NODE *reverseListIterator(NODE *pHead)
{
    NODE *preNODE = NULL;
    NODE *newHead = NULL;
    NODE *curNODE = pHead;

    while(curNODE != NULL)
    {
        NODE *tmp = curNODE->next;
        if(tmp == NULL)
        {
            newHead = curNODE;
        }
        curNODE->next = preNODE;
        preNODE = curNODE;
        curNODE = tmp;
    }

    return newHead;
}

//
static NODE *reverseListTail(NODE *pHead,NODE *newHead)
{
    NODE *pNext;

    if(pHead == NULL)
    {
        return newHead;
    }
    else
    {
        pNext = pHead->next;
        pHead->next = newHead;

        return reverseListTail(pNext,pHead);
    }
    
}

add
if (head = = NULL)

at the beginning of the function
return head;

.

Menu