我写的非常简单,就是遍历链表,然后保存在一个List中,再反向输出List。
之前面试的时候遇到过不新开空间,反向一个双向链表的题目,那个还是很有难度的。
class Node {
Node next;int value;
}
public class LinkList {
public static void main(String[] args) {
Node pHead = new Node();
pHead.value = 1;
createList(pHead);
printList(pHead);
printReverseList(pHead);
}
private static void printReverseList(Node pHead) {
ArrayList<Integer> list = new ArrayList<Integer>();
while (pHead!=null) {
list.add(pHead.value);
pHead = pHead.next;
}
for (int i=list.size()-1;i>=0;i--)
System.out.println(list.get(i));
}
private static void printList(Node pHead) {
while (pHead!=null) {
System.out.println(pHead.value);
pHead = pHead.next;
}
}
private static void createList(Node pHead) {
Node newNode;
Node nowNode = pHead;
for (int i=2;i<10;i++) {
newNode = new Node();
newNode.next = null;
newNode.value = i;
nowNode.next = newNode;
nowNode = newNode;
}
}
}