代码如下,已给出详细注释,主要思路就是先将链表反转,再遍历链表保存到数组中
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int[] reversePrint(ListNode head) { ListNode pre = null; //前一个节点指针 ListNode cur = head; //用于遍历的节点指针,即当前节点 ListNode temp = null; //一个临时指针,指向剩余链表的头节点 int count = 0; //用于记录节点个数,方便后续创建数组 //将链表原地逆转 while(cur != null){ temp = cur.next; //先保存后续链表的头 cur.next = pre; //将当前节点的下一节点指向上一节点 pre = cur; //将上一节点的引用指向单签节点 cur = temp; //将当前节点的引用指向后续链表的头 count++; //节点个数+1 } cur = pre; //此时cur为null,需要将cur指向上一个节点 int[] arr = new int[count]; int i = 0; //访问数组的索引 //将链表保存到数组中 while(cur != null){ arr[i] = cur.val; i++; cur = cur.next; } return arr; } //官方还可使用栈来解决,执行效果似乎没有上面那么好,不过也还不错 // public int[] reversePrint(ListNode head) { // Stack<ListNode> stack = new Stack<ListNode>(); // ListNode temp = head; // while (temp != null) { // stack.push(temp); // temp = temp.next; // } // int size = stack.size(); // int[] print = new int[size]; // for (int i = 0; i < size; i++) { // print[i] = stack.pop().val; // } // return print; // } }附上反转过程图解