单向链表反转

链表反转,返回反转后的链表头节点。记得在遍历过程中保存前面节点的指针

可以用递归和迭代两种方法来实现,在我学习的过程中,递归实现相对比较难以理解一些

递归法:

public static ListNode reverseList(ListNode head){

    if(head == null){ return head;}  //base case
    ListNode nHead = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return nHead;
}

递归算法就是显得比较优雅  

尾部递归算法:

private ListNode reverseList(ListNode head, ListNode prev){
    if(head == null) {return prev;}

    ListNode tempNode = head.next; // save pointer to the next guy 
    head.next = prev;
    return reverseList(tempNode,head);
}

public ListNode reverseList(ListNode head){
    return reverseList(head,null);
}

个人体会

对于链表的问题,方法比较固定,但涉及到边界检查问题,比较容易出错

方法:“runner” 也就是快慢指针法;递归

注意:检查输入参数是否为空指针。

原文地址:https://www.cnblogs.com/yeek/p/3441980.html