网址
信息
开题日期:2023.1.29
通过日期:2023.1.30
题目状态:通过
Java数组可把我害惨了= =
没想到p事这么多,学的时候没觉得,现在都忘完了,被报错一顿毒打。
而且这题比24题要麻烦一点,head为空和head.next为空的情况要分开讨论。
算法
遍历整个列表,并使用头插法重新插入,完成逆序。
运行代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//异常处理
if(head == null){
return new int[0];
}else if(head.next == null){
return new int[]{head.val};
}
// NewHead作为实际头
ListNode NewHead = new ListNode();
NewHead.next = head;
int list_len = 1; // 用于记录链表长度
// 使用头插法
ListNode p = new ListNode();
ListNode temp = new ListNode();
temp = head;
for(p = head.next;head.next!=null;p=head.next){
head.next = p.next;
NewHead.next = p;
p.next = temp;
temp = p;
list_len ++;
}
/*
System.out.print(list_len);
System.out.println("这是链表");
int test = 0;
for(p = NewHead.next;p!=null;p = p.next){
System.out.println(p.val);
System.out.print("test=");
System.out.println(test);
test ++;
}
System.out.println("下面是输出结果");
*/
int[ ] re_array = new int[list_len];
int index = 0;
for(p = NewHead.next;p!=null;p = p.next){
re_array[index] = p.val;
index ++;
}
return re_array;
}
}
DEBUG
bug1
Line 14: error: array dimension missing re_array = new int[];
解决方案
if(head == null){
return new int[0];
}else if(head.next == null){
return new int[]{head.val};
}
注意,静态初始化数组的时候括号里不能写数字,不然会报错。