No.3从头到尾打印链表 +反转链表

题目描述

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

我的第一反应是先按顺序写入到ArrayList中,再反向输出这个ArrayList,代码如下:

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
          	ArrayList<Integer> a = new ArrayList<Integer>();
	    	while(listNode != null) {
	    		a.add(listNode.val);
	    		listNode = listNode.next;
	    	}
	    	int len = a.size();
	    	ArrayList<Integer> b = new ArrayList<Integer>();
	    	for(int i = len-1;i>=0;i--) {
	    		
	    		b.add(a.get(i));
	    	}
	        return b;
    }
}

其中注意:Java集合如Map、Set、List等所有集合只能存放引用类型数据,它们都是存放引用类型数据的容器,不能存放如int、long、float、double等基础类型的数据。

其他博文中有提到栈的方法可以借鉴 :https://www.cnblogs.com/gl-developer/p/6438311.html

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
          	Stack<Integer> a = new Stack<Integer>();
	    	while(listNode != null) {
	    		a.push(listNode.val);
	    		listNode = listNode.next;
	    	}
	    	ArrayList<Integer> b = new ArrayList<Integer>();
	    	while(!a.empty()) {
	    	b.add(a.pop());}
	    	return b;
    }
}

ps:Stack是栈Vector的一个子类,而Vector和ArrayList一样是一种List,有序,且可重复。

题目描述

输入一个链表,反转链表后,输出新链表的表头。

思想是浙大的数据结构课里关于这道题的讲解,设置了两个指针

public class Solution {
    public ListNode ReverseList(ListNode head) {
       if( head == null){
		   return null;
	   }
	   ListNode blank = null;
	   ListNode old = null;
	    
	   while(head != null) {
		   old = head.next ;
		   head.next = blank;
		   blank = head;
		   head = old;
	   }
	   return blank;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值