链表反转,返回反转后的链表头节点。记得在遍历过程中保存前面节点的指针
可以用递归和迭代两种方法来实现,在我学习的过程中,递归实现相对比较难以理解一些
递归法:
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” 也就是快慢指针法;递归
注意:检查输入参数是否为空指针。
链表反转详解
本文深入讲解了链表反转的两种实现方法:递归法和迭代法。通过具体代码示例,详细解析了每种方法的实现过程及注意事项,特别强调了边界检查的重要性。
315

被折叠的 条评论
为什么被折叠?



