• 【剑指offer】面试题 6. 从尾到头打印链表


    面试题 6. 从尾到头打印链表

    NowCoder

    题目描述
    输入一个链表的头结点,从尾到头反过来打印出每个结点的值。

    Java 实现
    ListNode Class

    class ListNode {
    	int val;
    	ListNode next = null;
    
    	ListNode(int val) {
    		this.val = val;
    	}
    
    	@Override
    	public String toString() {
    		return val + "->" + next;
    	}
    }
    

    使用递归

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

    使用头插法

    import java.util.ArrayList;
    
    public class Solution {
    	public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    		ArrayList<Integer> res = new ArrayList<>();
    		ListNode head = new ListNode(-1);
    		while (listNode != null) {
    			ListNode newHead = listNode.next;
    			listNode.next = head.next;
    			head.next = listNode;
    			listNode = newHead;
    		}
    		while (head.next != null) {
    			res.add(head.next.val);
    			head = head.next;
    		}
    		return res;
    	}
    }
    

    使用栈

    import java.util.ArrayList;
    import java.util.Stack;
    
    public class Solution {
    	public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    		ArrayList<Integer> res = new ArrayList<>();
    		Stack<Integer> stack = new Stack<>();
    		while (listNode != null) {
    			stack.push(listNode.val);
    			listNode = listNode.next;
    		}
    		while (!stack.isEmpty()) {
    			res.add(stack.pop());
    		}
    		return res;
    	}
    }
    
  • 相关阅读:
    设计模式之实现状态模式
    一定要记住的OO设计原则:
    设计模式之实现命令模式
    设计模式之实现迭代器模式
    设计模式之实现观察者模式
    设计模式之实现策略模式
    设计模式之实现组合模式
    设计模式之实现几种工厂模式
    设计模式之实现装饰者模式
    pygame学习笔记(3)——时间、事件、文字
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10930162.html
Copyright © 2020-2023  润新知