剑指 Offer 06. 从尾到头打印链表(自我分析)

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

原网址:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

方法一:利用栈的方法

将头和尾调换的方法,和栈的先进后出的思想很相似。

可以看遍历列表,把列表里的元素存入到栈中(入栈push);然后在逐个取出放入结点(出栈pop)

  1. Stack的基本使用初始化:Stack stack=new Stack

  2. 判断是否为空:stack.empty()

  3. 取栈顶值(不出栈):stack.peek()

  4. 进栈:stack.push(Object);

  5. 出栈:stack.pop();


  Definition for singly-linked list.
  public class ListNode {
      int val;
     ListNode next;
      ListNode(int x) { val = x; }
  }
 
class Solution {
    public int[] reversePrint(ListNode head) {
		Stack<ListNode> st =new Stack<ListNode>();//定义一个栈
		ListNode node = head; //定义一个“指针”
		while(node!=null) {
			st.push(node); //如果结点不为空,就将它推入栈
			node=node.next; //“指针”指向下一个结点
		}
	
        
        int size = st.size();
        int[] newList = new int[size];//定义一个数组,数组长度为栈中存在的元素数
        for (int i = 0; i < size; i++) {
            newList[i] = st.peek().val;//将栈顶元素赋给数组
            st.pop();//栈顶元素出栈
        }
        
        return newList;
		
	}
}

方法二:递归

 所谓递归的思想,就是函数在自己里面不断的调用自己;

只有满足停止条件,才停止调用,否则将一直循环下去。

列如:

当递归结束时,将先执行最后生成的函数,4->3->2->1

class Solution {
    ArrayList<Integer> newList = new ArrayList<Integer>();//用ArrayList来操作
    public int[] reversePrint(ListNode head) {
        last(head);
        int[] res = new int[newList.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = newList.get(i); //遍历ArrayList的元素
        return res;
    }
    void last(ListNode head) {
        if(head == null) return; //递归结束判断
        last(head.next);  //掉用自己,每调用一次,就把下一个元素推入
        newList.add(head.val);  //由于先执行新开的函数,所以是先推入最后的数
    }
}

方法三:列表反向输入到数组中

先确定链表的长度,创建一个和长度一样长的数组。

用for循环把链表反向输入到数组中

class Solution {

    public static int[] reversePrint(ListNode head) {
        ListNode node = head; //创建一个“指针”,指向链表头
        int length = 0;
        while (node != null)  //用while循环来确定数组长度
        {
            length++;
            node = node.next;
        }
        int[] nums = new int[length];//创建一个和链表一样长的数组
        node = head; //将“指针”归为,重新指向链表头
        for (int i = length - 1; i >= 0; i--) //将链表倒放入数组
         {
            nums[i] = node.val;
            node = node.next;
        }
        return nums;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值