题解 | #从尾到头打印链表#
从尾到头打印链表
http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
思路
M1-栈
栈的特点是先入后出,所以可以遍历节点并且入栈。然后挨个弹出栈顶节点,并将节点添加到List集合中进行返回。
M2-递归
递归法的特点就是递归到尾节点,然后首先将尾节点添加到list中,然后将其list返回,然后通过引用传递的方式,每次递归都会返回一个list引用,就做到了从最后进行返回(例如:[3] -> [3,2] -> [3,2,1]),最终将最终引用返回给调用者,也就实现了反转打印。
结果
M1->运行时间:47ms 占用内存:10560KB
M2->运行时间:45ms 占用内存:10816KB
代码-M1
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode == null) return new ArrayList<Integer>();
if (listNode.next == null) return new ArrayList<Integer>(listNode.val);
// 解决方法一:栈特性,先进后出
Stack<Integer> stack = new Stack<>();
ListNode currentNode = listNode;
// 入栈
while (currentNode != null){
stack.push(currentNode.val);
currentNode = currentNode.next;
}
// 出栈
ArrayList<Integer> list = new ArrayList<>();
while (!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}代码-M2
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
// 解决方法二:递归
// 如果当前节点为null
if (listNode == null) return new ArrayList<>();
while (true){
// 构造集合
ArrayList<Integer> list = new ArrayList<>();
// 如果当前节点为null,那么直接continue
// 如果当前节点不是最后一个节点,那么就向下递归寻找,获取后续反转数据集合
if (listNode.next != null){
list = printListFromTailToHead(listNode.next);
}
// 向此节点后已经反转好的集合中添加该节点的值
list.add(listNode.val);
return list;
}
}
查看20道真题和解析