题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题目分析:
方法1:
取出元素,放在ArrayList<>()中,然后再创建一个ArrayList<>(),倒序遍历放进去。 时间复杂度 O(2n) => O(n) 空间复杂度 O(n)
方法2:
取出元素,放在ArrayList<>()中,使用插入指定位置的add(index,value),方法 时间复杂度 O(n) 空间复杂度 O(n)
方法3:
很明显的先进先出,使用栈实现 时间复杂度 O(n) 空间复杂度 O(n)
代码实现
public class _03_PrintList {
public static void main(String[] args) {
SelfList selfList = new SelfList();
selfList.add(new ListNode(12));
selfList.add(new ListNode(13));
selfList.add(new ListNode(14));
selfList.add(new ListNode(15));
selfList.add(new ListNode(16));
ListNode root = selfList.getRoot();
ArrayList<Integer> res = printListFromTailToHead(root);
ArrayList<Integer> res2 = printListFromTailToHeadStack(root);
ArrayList<Integer> res3 = printListFromTailToHead2(root);
for (Integer r : res) {
System.out.print(r + " ");
}
System.out.println();
for (Integer r : res2) {
System.out.print(r + " ");
}
System.out.println();
for (Integer r : res3) {
System.out.print(r + " ");
}
}
public static ArrayList<Integer> printListFromTailToHeadStack(ListNode listNode) {
if (listNode == null) {
return new ArrayList<Integer>();
}
ListNode temp = listNode;
Stack<Integer> stack = new Stack<>();
while (temp != null) {
stack.push(temp.val);
temp = temp.next;
}
ArrayList<Integer> res = new ArrayList<>();
while (!stack.isEmpty() && stack.size() != 0) {
res.add(stack.pop());
}
return res;
}
public static ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
if (listNode == null) {
return new ArrayList<Integer>();
}
ArrayList<Integer> res = new ArrayList<>();
ListNode temp = listNode;
while (temp != null) {
res.add(0, temp.val);
temp = temp.next;
}
return res;
}
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode == null) {
return new ArrayList<Integer>();
}
ArrayList<Integer> al = new ArrayList<>();
ArrayList<Integer> res = new ArrayList<>();
ListNode temp = listNode;
while (temp != null) {
al.add(temp.val);
temp = temp.next;
}
for (int i = al.size() - 1; i >= 0; i--) {
res.add(al.get(i));
}
return res;
}
}
class SelfList {
private ListNode root = new ListNode(0);
public ListNode getRoot() {
return root;
}
public void printListNode() {
if (root == null || root.next == null) {
return;
}
ListNode temp = root;
while (temp.next != null) {
System.out.println(temp.next);
temp = temp.next;
}
}
public void add(ListNode node) {
ListNode temp = root;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
'}';
}
}
测试
16 15 14 13 12 0
16 15 14 13 12 0
16 15 14 13 12 0
网友评论