输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
class method{
public static ListNodeDemo head = new ListNodeDemo(0);
public int[] reverse() {
int[] nums = {};
if (head.next == null) {
return nums; //链表为空
}
ListNodeDemo temp = head.next;//定义一个辅助指针
int count = 1; //定义一个计数变量
while (true) {
if (temp.next == null) {//遍历结束
break;
} else if (temp.next != null) {
count++; //得到链表中的所有个数
}
temp = temp.next;
}
temp = head.next;//复原
int[] arr=new int[count]; //开辟一个空间为count的数组
//开始打印反转
int i = count-1;
while(temp!=null){ //链表遍历到最后了
arr[i--] = temp.id;
temp = temp.next;
}
return arr;
}
}