public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
//递归终止条件是当前为空,或者下一个节点为空
if(head==null || head.next==null) {
return head;
}
//这里的cur就是最后一个节点
ListNode cur = reverseList(head.next);
//这里请配合动画演示理解
//如果链表是 1->2->3->4->5,那么此时的cur就是5
//而head是4,head的下一个是5,下下一个是空
//所以head.next.next 就是5->4
head.next.next = head;
//防止链表循环,需要将head.next设置为空
head.next = null;
//每层递归函数都返回cur,也就是最后一个节点
return cur;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
static class Test {
public static void main(String[] arg) {
ListNode start = new ListNode(1);
ListNode pre = start;
for (int i = 2; i < 6; i++) {
ListNode curr = new ListNode(i);
pre.next = curr;
pre = curr;
}
ListNode initNode = start;
while (start != null){
System.out.print(start.val + " > ");
start = start.next;
}
System.out.println(" null ");
ReverseLinkedList r = new ReverseLinkedList();
ListNode newNode = r.reverseList(initNode);
while (newNode != null){
System.out.print(newNode.val + " > ");
newNode = newNode.next;
}
System.out.print(" null ");
}
}
}
反转列表测试(别人的实现)
最新推荐文章于 2022-01-01 09:03:50 发布
本文详细探讨了如何反转一个列表,分析了一种他人的实现方式,并通过测试验证其正确性和效率。内容涵盖列表反转的基本概念,算法原理以及实际应用。
114

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



