/**
* 题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
* 思路:1)从头到尾遍历,并改变链表顺序
* 2)用栈实现后进先出
*/
public class E5 {
public static void main(String[] args) {
//int a[] = new int[]{1,2,3,4,5,6,7,8,9,10};
int a[] = new int[]{};
Node head = createLinkFromArray(a);
printListReversingly(head);
}
private static void printListReversingly(Node head) {
if (head == null) return;
Stack<Node> stack = new Stack<>();
Node currentNode = head;
while (currentNode != null) {
stack.push(currentNode);
currentNode = currentNode.getNext();
}
while (!stack.isEmpty()) {
System.out.print(stack.pop().getKey()+" ");
}
}
private static Node createLinkFromArray(int[] a) {
if (a==null || a.length ==0) {
return null;
}
Node head = new Node(a[0]);
Node current = head;
for (int i=1;i<a.length;i++) {
current.setNext(new Node(a[i]));
current = current.getNext();
}
return head;
}
}
class Node {
private int key;
private Node next;
public Node(){}
public Node(int key) {
this.key = key;
}
public Node(int key, Node next) {
this.key = key;
this.next = next;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
10-18
6万+
03-23
385
09-15
132