Inversion Algorithm of Singly Linked List with Leading Node

What is inversion? For a better understanding, look directly at the picture: (data elements are randomly selected)

Before inversion:
After inversion:

The detailed steps are as follows: (Using head insertion method)

①:

The head node does not move, and the pointer p points to the next bit of the head node, that is, p = head->next; the
q pointer points to the next bit of the p pointer, that is, q = p -> next;
since the a element is reversed, in The last bit, so the next value of a should be empty, that is, p->next = NULL;

②:

The pointer p points to the position pointed to by q, that is, p = q; the q pointer moves backward one bit, that is, q = q->next; the
next value pointed to by the head node (that is, the address of the next element) is assigned to the next of p Value, that is, p->next = head->next;
change the value of next of the head node, that is, head->next = p;

③:

Loop the above steps until the next value of the q pointer is NULL and no longer loop.

The detailed code is as follows: (the code is not unique, it is for reference only)

void Traverse(Lnode *L)
{
    Lnode *p,*q;
if(L->next == NULL)//判断是否为空链表
   return ERROR;
p = L->next;
q = q->next;
p->next = NULL;
while(q)
{
    p = q;
    q =q->next;
    p->next = L->next;
    L->next = p;
}
}

Guess you like

Origin blog.csdn.net/qq_69424518/article/details/128581150