输入一个链表,从尾到头打印链表每个节点的值

1、使用栈:

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arr = new ArrayList();
        Stack<Integer> stack = new Stack();
        while(listNode != null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()){
            int value = stack.pop();
            arr.add(value);
        }
        return arr;
    }
}

别忘了导入包:java.util.Stack;
Stack的声明别忘了类型:
Stack stack = new Stack();
它的方法:push()和pop();

2、使用递归:

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arr = new ArrayList();
        if(listNode == null){
            return arr;
        }
        arr = printListFromTailToHead(listNode.next);
        arr.add(listNode.val);
        return arr;
    }
}

3、使用Collections.reverse()

import java.util.ArrayList;
import java.util.Collections;

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arr = new ArrayList();
        while(listNode != null){
            arr.add(listNode.val);
            listNode = listNode.next;
        }
        Collections.reverse(arr);

        return arr;
    }
}

4、使用头插法

import java.util.ArrayList;


public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> arr = new ArrayList();
        ListNode head = new ListNode(-1);

        while(listNode != null){
            //注意这里
            ListNode pre = new ListNode(listNode.val);
            pre.next = head.next;
            head.next = pre;

            listNode = listNode.next;
        }
        ListNode p = head.next;
        while(p != null){
            arr.add(p.val);
            p = p.next;
        }

        return arr;
    }
}

使用头插法,可以让它的顺序反过来!

猜你喜欢

转载自blog.csdn.net/xuchonghao/article/details/80056260
今日推荐