题目:
输入一个链表的头节点,从尾到头反过来打印每个节点的值。链表节点定义为:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
思路一(破坏原链表型):
声明reverse结点引用变量指向逆序链表的头节点,first结点引用变量指向原链表的头节点,second指向first的下一个节点。每次将first结点插入于逆序链表的头节点之前。
代码(牛客网AC):
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode reverse = null;
ListNode first = listNode;
while(first != null){
ListNode second = first.next;
first.next = reverse;
reverse = first;
first = second;
}
ArrayList<Integer> list = new ArrayList<>();
while(reverse != null){
list.add(reverse.val);
reverse = reverse.next;
}
return list;
}
}
性能:时间复杂度为O(n)。
思路二(不破坏原链表):
通过栈使得链表逆序。
代码(牛客网AC):
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> reverse = new ArrayList<>();
Stack<ListNode> stack = new Stack<>();
while(listNode != null){
stack.push(listNode);
listNode = listNode.next;
}
while(!stack.empty()){
reverse.add(stack.pop().val);
}
return reverse;
}
}
性能: 时间复杂度为O(n)。