[剑指offer_06] 从尾到头打印链表

[剑指offer_06] 从尾到头打印链表

1.从尾到头打印链表

题目描述:输入一个链表,从尾到头打印链表每个节点的值。
思路:借助栈实现,或使用递归的方法。

2.借助栈实现

/**
 * 解法一:利用栈输出
 *
 * @param head 头节点
 * @return list集合
 */
public static ArrayList<Integer> reversePrintList1(ListNode head) {
    ArrayList<Integer> list = new ArrayList<>();
    Stack<ListNode> stack = new Stack<>();//创建栈,先进后出
    while (head != null) {
        stack.push(head);//压栈
        head = head.next;
    }
	//栈非空时继续弹出
    while (!stack.isEmpty()) {
        list.add(stack.pop().val);//出栈放入集合数组
    }
    return list;
}


/**
 * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
 * 输入:head = [1,3,2]
 * 输出:[2,3,1]
 *
 * @param head 头节点
 * @return 数组集合
 */
public static int[] reversePrintList2(ListNode head) {
    Stack<ListNode> stack = new Stack<>();//创建栈,先进后出
    while (head != null) {
        stack.push(head);//压栈
        head = head.next;
    }

    int size = stack.size();
    int[] print = new int[size];

    for (int i = 0; i < size; i++) {
        print[i] = stack.pop().val;
    }
    return print;
}

3.利用递归实现

/**
 * 解法二:递归(其实底层还是栈)
 *
 * @param head 头节点
 * @return list集合
 */
public static ArrayList<Integer> reversePrintList3(ListNode head) {
    ArrayList<Integer> list = new ArrayList<>();

    if (head != null) {
        if (head.next != null) {
            list = reversePrintList3(head.next);
        }
        list.add(head.val);
    }
    return list;
}

/**
 * 递归(数组)
 */

private ArrayList<Integer> tmp = new ArrayList<>();

public int[] reversePrintList4(ListNode head) {
    recur(head);
    //重新创建一个等大小的数组进行遍历赋值
    int[] res = new int[tmp.size()];
    for (int i = 0; i < res.length; i++) {
        res[i] = tmp.get(i);
    }
    return res;
}

private void recur(ListNode head) {
    if (head != null) {
        if (head.next != null) {
            recur(head.next);
        }
        tmp.add(head.val);
    }
}

4.测试用例

@Test
public void test6(){
    ListNode node1 = new ListNode(4);
    ListNode node2 = new ListNode(1);
    ListNode node3 = new ListNode(5);

    node1.next = node2;//什么节点之间的关系
    node2.next = node3;

    System.out.println("解法一:利用栈输出,反转打印:" + ReversePrintList6.reversePrintList1(node1));
    System.out.println("解法一:利用栈输出,反转打印:" + Arrays.toString(ReversePrintList6.reversePrintList2(node1)));//数组需要转成字符串输出
    System.out.println("解法二: 递归,反转打印: " + ReversePrintList6.reversePrintList3(node1));
    ReversePrintList6 obj = new ReversePrintList6();
    System.out.println("解法二: 递归,反转打印: " + Arrays.toString(obj.reversePrintList4(node1)));//数组需要转成字符串输出

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值