zoukankan      html  css  js  c++  java
  • 从尾到头打印链表

    题目描述
    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

    方法一
    采用栈的思想,先进后出。

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

    方法二
    采用递归的思想,递归到最后一个值,在依次添加至List

    	ArrayList<Integer> list = new ArrayList<Integer>();
    	
    	public ArrayList<Integer> printListFromTailToHead_2(ListNode listNode) {
    		if(listNode != null) {
    			printListFromTailToHead_2(listNode.next);
    			list.add(listNode.val);
    		}
    
    		return list;
    	}
    

    方法三
    从头到尾添加至列表中,在从0到(list.length)/2下标进行替换

    	public ArrayList<Integer> printListFromTailToHead_3(ListNode listNode) {
    		ArrayList<Integer> list = new ArrayList<Integer>();
    		
    		int temp;
    		while(listNode != null) {
    			list.add(listNode.val);
    			listNode = listNode.next;
    		}
    		
    		for (int i = 0; i < (list.size() / 2); i++) {
    			temp = list.get(i);
    			int j = list.size() - i - 1;
    			list.set(i, list.get(j));
    			list.set(j, temp);
    		}
    		
    		return list;
    	}
    
  • 相关阅读:
    【LeetCode】206. Reverse Linked List
    【LeetCode】160. Intersection of Two Linked Lists
    【LeetCode】190. Reverse Bits
    【LeetCode】165. Compare Version Numbers
    继续深入《一张神奇的图》
    Base64编码简介
    证明任意两个正整数相等(伪命题)
    DEADBEEF
    汉诺塔问题
    字符编码(2)-- 程序中的编码
  • 原文地址:https://www.cnblogs.com/lishanlei/p/10707764.html
Copyright © 2011-2022 走看看