题目描述
输入一个链表,按链表从尾到头的顺序返回一个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;
}
}