我写的非常简单,就是遍历链表,然后保存在一个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;
}
}
}
本文介绍了一种通过创建链表并使用辅助列表来实现链表逆序输出的方法。首先创建了一个链表,并填充了从2到9的整数节点。接着通过遍历链表将每个节点的值保存到一个ArrayList中,最后反向遍历这个ArrayList并打印出链表的逆序值。
521

被折叠的 条评论
为什么被折叠?



