剑指Offer——从尾到头打印链表多种解法(JAVA)以及相应知识拓展

先讲一讲ArrayList<Integer>:
(1) Integer类型的ArrayList数组,ArrayList数组,可以动态改变数组的长度,来自System.Collections;
(2) 由于扩容会浪费内存空间,速度较普通数组慢(数据满时自动增加一倍)
(3) ArrayList的一些方法:.
        count(获取数组长度)
        .add(xxx)(添加元素)
        remove(object xxx)(移除值为xxx的元素)
        removeAt(int xxx)(移除索引为xxx的元素)
        removerange(int xxx,int n)(移除从xxx索引开始后的n个元素)contains(object xxx) (查找xxx元素,存在返回true)
        al.IndexOf(object obj)(从0开始查找obj元素,只第一个obj元素,并返回起在数组中的位置,如果不存在,返回-1)
        al.IndexOf(object obj,int startIndex);(从startIndex开始查找obj元素,只第一个obj元素,并返回起在数组中的位置)

        al.IndexOf(object obj,int startIndex,int count)( 从startIndex开始想后查找count个元素,如果存在obj元素,则返回其在数组中的位置)。

参考:https://www.cnblogs.com/lxqiaoyixuan/p/7156936.html

Ponit 1 利用堆栈的push和pop来实现:

import java.util.ArrayList;

import java.util.Stack;//需要添加一个Stack的包

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         ArrayList<Integer> newlist = new ArrayList<Integer>();
        //新建一个栈,通过push和pop实现
         Stack<ListNode> newstack = new Stack<ListNode>();
        //检测链表是否为空,若为空,将无法继续执行
        if(listNode == null)
            return newlist;
        else
        {
            while(listNode != null)
            {
                //当前节点压栈
                newstack.push(listNode);
                listNode=listNode.next;//后移
            }
            //知道栈为空,否则一路POP
            while(!newstack.isEmpty())
            {
                //添加出栈元素到数组
               newlist.add(newstack.pop().val);
            }     
        return newlist;
        }
    }

Ponit 2 利用递归来实现(由于一开始给的是ArrayList<Integer>类型的函数,所以得重新定义一个函数用来递归):

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         ArrayList<Integer> newlist = new ArrayList<Integer>();
        digui(listNode,newlist);
        return newlist;
    }
    public void  digui(ListNode listNode,ArrayList<Integer> curlist)
    {
            if(listNode == null)
            return;
        // 此处要特别注意,如果1和2进行调换,则会出现正序
          /* 1 */  digui(listNode.next,curlist);
          /* 2 */  curlist.add(listNode.val);
    }

}

此处:我将给大家提供一个单链表知识的链接,涉及到了一些最基本的单链表操作(个人觉得很有用)

https://blog.csdn.net/qq_34992845/article/details/53948486

这是我第一篇博客,我也是在边学做写,希望不好的地方能多给个建议,有用的也能夸夸我


猜你喜欢

转载自blog.csdn.net/qq_41527198/article/details/79930191