我们可以声明一个空节点,然后把原始节点的第一个节点的 next 引用指向这个空节点就是我们想要的效果了
1 2 3 4 5 6 7 8 9 10
publicclassReverseList{ publicstaticvoidmain(String[] args){ ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null)))));
为了遍历后续的节点,我们需要在 head.next = empty 之前用另一变量来持有这个 next 引用 ListNode holder1 = head.next;。处理第二个节点的时候,我们其实重复了之前的操作,将它单独拆下来,然后拼接到 head 前面即可。按照这个思路,我可以直接联想使用 while 循环处理这个问题
publicclassReverseList{ publicstaticvoidmain(String[] args){ ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null))))); System.out.println(head);
ListNode result = null; ListNode holder;
while(head != null) { holder = head.next; head.next = result; result = head; head = holder; }
/** * input: 1->2->3->4->5->NULL * output: 5->4->3->2->1->NULL */ publicclassReverseListSample{ publicstaticvoidmain(String[] args){ ListNode fir = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); System.out.println(fir.toString());
ListNode ret = reverseList(fir); System.out.println(ret.toString()); }
publicstatic ListNode reverseList(ListNode head){ ListNode next; ListNode pre = null; while (Objects.nonNull(head)) { next = head.next; head.next = pre; pre = head; head = next; } return pre; } }