迭代
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head==null||head.next==null){
return head;
}
ListNode newHead = null;
while(head.next!=null){
ListNode tem = head;
head = head.next;
tem.next = newHead;
newHead = tem;
}
head.next = newHead;
return head;
}
}
递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head==null||head.next==null){
return head;
}
ListNode res = ReverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}
这篇博客探讨了两种链表反转的方法,分别是迭代和递归。迭代方案通过改变链表节点的指针方向逐步完成反转,而递归方案则利用递归调用自身实现反转。这两种方法各有特点,适用于不同的编程场景。
1515

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



