• 单链表
    • 单链表就地翻转

    单链表

    单链表就地翻转

    递归算法:

    1. void reverse(struct list_node *head)
    2. {
    3. if(NULL == head || NULL == head->next)
    4. return;
    5. reverse1(head->next);
    6. head->next->next = head;
    7. head->next = NULL;
    8. }

    非递归算法:

    1. void reverse2(struct list_node *head)
    2. {
    3. if (NULL == head)
    4. {
    5. return;
    6. }
    7. list_node *curr = head;
    8. list_node *next = head->next;
    9. list_node *prev = NULL;
    10. while (next != NULL) {
    11. curr->next = prev;
    12. prev = curr;
    13. curr = next;
    14. next = curr->next;
    15. }
    16. curr->next = prev;
    17. }