首页 > 其他 > 详细

剑指 Offer 06. 从尾到头打印链表

时间:2020-06-28 21:20:58      阅读:70      评论:0      收藏:0      [点我收藏+]
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * @Class ReversePrint
 * @Description 剑指 Offer 06. 从尾到头打印链表
 * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
 *
 * 示例 1:
 * 输入:head = [1,3,2]
 * 输出:[2,3,1]
 *
 * 限制:
 * 0 <= 链表长度 <= 10000
 * @Author
 * @Date 2020/6/28
 **/
public class ReversePrint {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
}
/**
 * 解法1:利用栈
 */
public static int[] reversePrint(ListNode head) {
	ListNode listNode = head;
	Stack<Integer> integerDeque =new Stack<>();
	int count =0;
	while (listNode!= null){
		integerDeque.push(listNode.val);
		listNode = listNode.next;
		count++;
	}
	int[] ans = new int[count];
	for (int i = 0; i <count ; i++) {
		ans[i] = integerDeque.pop();
	}
	return ans;
}
/**
 * 解法2:利用递归
 */
public static int[] reversePrint(ListNode head) {
	LinkedList<Integer> linkedList = new LinkedList<>();
	reversePrint(head,linkedList);
	int size = linkedList.size();
	int[] ans = new int[size];
	for (int i = 0; i < size; i++) {
		ans[i]= linkedList.pop();
	}
	return ans;
}

private static LinkedList<Integer> reversePrint(ListNode listNode, LinkedList linkedList){
	if(listNode==null) return null;
	linkedList.add(listNode.val);
	return reversePrint(listNode.next,linkedList);
}
// 测试用例
public static void main(String[] args) {
	ListNode listNode11 = new ListNode(1);
	ListNode listNode12 = new ListNode(3);
	listNode11.next = listNode12;
	ListNode listNode13 = new ListNode(2);
	listNode12.next = listNode13;
	listNode13.next = null;

	int[] ans = reversePrint(listNode11);
	System.out.println("demo01 result:");
	for (int val : ans){
		System.out.print(" "+val);
	}
	System.out.println("");
}

剑指 Offer 06. 从尾到头打印链表

原文:https://www.cnblogs.com/fyusac/p/13204886.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!