题目:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:
程序1:笨方法,利用for循环,依次将链表的值倒序存入新链表中。
程序2:利用栈(先进后出)来实现。
程序:
程序1:
import java.util.ArrayList;
class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
public class subject3 {
public static ArrayList<Integer> printList(ListNode listNode){
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> newList = new ArrayList<Integer>();
ListNode temp = listNode;
while(temp != null){
list.add(temp.val);
temp = temp.next;
}
for(int i = list.size() - 1; i >= 0; i --){
newList.add(list.get(i));
}
return newList;
}
public static void main(String args[]){
ListNode ln1 = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
ln1.next = ln2;
ln2.next = ln3;
System.out.println(printList(ln1));
}
}
程序2:
import java.util.ArrayList;
import java.util.Stack;
class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
public class subject3 {
public static ArrayList<Integer> printList(ListNode listNode){
Stack<Integer> st = new Stack<Integer>();
ArrayList<Integer> newList = new ArrayList<Integer>();
ListNode temp = listNode;
while(temp != null){
st.push(temp.val);
temp = temp.next;
}
while(! st.isEmpty()){
newList.add(st.pop());
}
return newList;
}
public static void main(String args[]){
ListNode ln1 = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
ln1.next = ln2;
ln2.next = ln3;
System.out.println(printList(ln1));
}
}