单链表逆置算法解析_逆置

单链表逆置算法解析_传智播客_02

单链表逆置算法解析_链表_03

单链表逆置算法解析_逆置_04

void reverse(struct list *ls)//链表逆置

{

    if (ls->next == NULL)

        return;//只有一个首节点,不需要逆置

 

    if (ls->next->next == NULL)

        return;//也不需要逆置

 

    struct list *last = ls->next;//逆置后ls->next就成了最后一个节点了

 

    struct list *pre = ls;//上一个节点的指针

    struct list *cur = ls->next;//当前节点的指针

    struct list *next = NULL;//下一个节点的指针

    while(cur)

    {

        next = cur->next;

        cur->next = pre;

        pre = cur;

        cur = next;

    }

 

    ls->next = pre;

    last->next = NULL;

}