第三题:从头到尾打印链表
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
解析:由题意可以想到的一种解法,将链表反转后从头到尾进行遍历。 如果面试官对链表要求不能够进行修改怎么办?也就是说原链表不能进行改变。
例如: 1 -> 5 -> 6 -> 7 结果: 7 6 5 1
看到这样的结果你是否会想到 FILO?所以使用栈空间解决这个问题正好。
具体代码实现如下:
// 链表结构
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
//这种是使用额外空间栈的解法
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
//这种是反转链表的解法
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
ListNode head = listNode;
ListNode pre = null;
ListNode next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
while(pre != null){
list.add(pre.val);
pre = pre.next;
}
return list;
}
}
// 这是种递归的写法
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode != null){
if(listNode.next != null){
printListFromTailToHead(listNode.next);
}
list.add(listNode.val);
}
return list;
}
}
NowCoder(Online Coding, Please Click)