从头到尾打印链表

第三题:从头到尾打印链表

 

题目描述

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

 

解析:由题意可以想到的一种解法,将链表反转后从头到尾进行遍历。 如果面试官对链表要求不能够进行修改怎么办?也就是说原链表不能进行改变。

例如: 1 -> 5 -> 6 -> 7     结果: 7  6  5  1 

看到这样的结果你是否会想到 FILO?所以使用栈空间解决这个问题正好。

 

具体代码实现如下:


 

// 链表结构
public class ListNode {  
         int val;  
         ListNode next = null;  
  
         ListNode(int val) {  
             this.val = val;  
         }  
 }
//这种是使用额外空间栈的解法
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        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;
    }
}
//这种是反转链表的解法
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        ListNode head = listNode;
        ListNode pre = null;
        ListNode next = null;
        while(head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        while(pre != null){
            list.add(pre.val);
            pre = pre.next;
        }
        return list;
    }
}
// 这是种递归的写法
public class Solution {    
    ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode != null){
            if(listNode.next != null){
                printListFromTailToHead(listNode.next);
            }
            list.add(listNode.val);
        }
        return list;
    }
}

NowCoder(Online Coding, Please Click)

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值