package LinkedList;
public class ReverseLinkedList {
//输入一个链表的头节点,从尾到头反过来返回每个节点的值
//思路:把链表遍历放入数组中,然后反向遍历数组
public int[] reverse(Node head){
if (head==null){
System.out.println("链表为空");
}
int size=0;
Node temp=head;
while (temp!=null){
temp=temp.next;
size++;
}
temp=head;//这个条件必须带,别忘了
int[] arr = new int[size];
while (temp!=null){
arr[size-1]=temp.val;
temp=temp.next;
size--;
}
return arr;
}
}
class Node{
Node next;
int val;
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
public Node(int val) {
this.val = val;
}
}
|