03_printListFromTailToHead

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

package com.hwx.swordToOffer._03_printListFromTailToHead;
import java.util.ArrayList;
import java.util.Stack;
/*
 * 题目描述:
 * 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
 */
public class Solution {
	
	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = new ListNode(2);
		ListNode node3 = new ListNode(3);
		ListNode node4 = new ListNode(4);
		node1.next=node2;
		node2.next=node3;
		node3.next=node4;
		System.out.println(printListFromTailToHead(node1));
	}
	
	/*
	 * 我的方法:使用栈"先进后出"的结构
	 */
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode==null){
        	//注意:这里不能直接返回null,否则测试案例不通过,因为测试案例是将ArrayList进行打印,
        	//输入null,返回[]不是null;也可以不写这句判断语句,为null时直接返回空的ArrayList
        	return new ArrayList<Integer>();
        }
        Stack<Integer> stack=new Stack<>();
        ListNode cur=listNode;
        while(cur!=null) {
        	stack.push(cur.val);
        	cur=cur.next;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while(stack.size()>0) {
        	list.add(stack.pop());
        }
        return list;
    }

    /*
     * 不使用栈结构,直接在原链表上进行操作,不难但也有一点技术含量,要会掌握
     */
     public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
            ArrayList<Integer> list=new ArrayList<Integer>();
            ListNode pre=null;//即新链表的头节点
            ListNode next=null;//当前节点的下一个节点
            
            while(listNode!=null){
                next=listNode.next;//重要!!!!保存当前节点的下一个节点
                listNode.next=pre;//将当前节点连接到新链表的头部,即当前节点为的下一节点为新链表的头节点
                pre=listNode;//在将新链表的头节点前移一个,来到最新的头节点
                listNode=next;//当前节点往后移动,为原始链表的下一个节点
                
                //while循环结束后listNode指向null,pre指向新链表的头节点
            }
            
            while(pre!=null){
                list.add(pre.val);
                pre=pre.next;
            }
            return list;
        }
     
}
class ListNode {
    int val;
     ListNode next = null;

     ListNode(int val) {
        this.val = val;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值