• 剑指offer-从尾到头打印链表


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

      我一开始想到的是遍历这个链表,遍历过程中用一个ArrayList保存里面的值,然后再从尾到头遍历这个ArrayList,存储在新的ArrayList里面返回。

          

    //使用另外一个ArrayList存储链表的方法
    	public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    			ArrayList<Integer> list=new ArrayList<Integer>();
    			ListNode head=listNode;
    			while(head!=null) {
    				list.add(head.val);
    				head=head.next;
    			}
    			ArrayList<Integer> result=new ArrayList<Integer>();
    			for(int i=list.size()-1;i>=0;i--) {
    				result.add(list.get(i));
    			}
    			return result;
    }
    

      后来看了剑指offer,发现其实如果是从尾到头打印链表,由于这个是单向链表,并没有存储前一个链表的值,所以我们只能先从头到尾打印链表,所谓的“后进先出”,这时候就可以联想到栈这个数据结构。

          Stack类是Vector类的子类.Vector类与ArrayList类的区别是,Vector是线程安全的,即在多线程的情况下,允许多个线程同时修改vector,但ArrayList是线程不安全的,需要在代码里保证其同步性,即一次只能有一个线程访问ArrayList.所以Vector的性能是比ArrayList要低的。

    public static ArrayList<Integer> printListFromTailToHeadWithStack(ListNode listNode) {
    		Stack<Integer> stack = new Stack<Integer>();
    		ArrayList<Integer> list=new ArrayList<Integer>();
    		ListNode head=listNode;
    		while(head!=null) {
    			stack.push(head.val);
    			head=head.next;
    		}
    		while(!stack.isEmpty()) {
    			Integer item=stack.pop();
    			list.add(item);
    		}
    		return list;
    }
    

      由栈又很容易联想到递归。

    	static ArrayList<Integer> result;
    	public static void print(ListNode listNode) {
    		if(listNode!=null) {
    			
    			print(listNode.next);
    			result.add(listNode.val);
    		} 
    	}
    	//使用递归
    	public static ArrayList<Integer> printListFromTailToHeadWithRecursion(ListNode listNode) {
    		result=new ArrayList<Integer>();
    		print(listNode);
    		return result;
    }
    

      

  • 相关阅读:
    创建user keywords
    robotframework中list和dict variables
    安装sshlibrary库报错:Could not find a version that satisfies the requirement
    【转】用U盘制作启动盘后空间变小的恢复方法
    docker "exec format error"
    window cmd 设置IP,关闭防火墙,开启远程桌面
    Linux iptables
    python logging 模块
    docker 命令
    python xmlrpc入门
  • 原文地址:https://www.cnblogs.com/qingfei1994/p/4834810.html
Copyright © 2020-2023  润新知