java - 我手动编写Nodelist并尝试反转它为什么这里总是出现空指针异常,我试图手动创建ListNode
问题描述
第一种是手动listnode类,第二种是list reverse类,然后用main类来执行!我的想法是创建一个新的 ListNode 并将其头部传递给 ReverseList 方法,在该方法中它将反转创建的 ListNode 中的指针,然后迭代反转的列表
public class ReverseList {
//Innerclass for a manual ListNode
class ListNode<E> {
ListNode<E> next;
E val;
public ListNode(E value) {
val = value;
next = null;
}
public ListNode(E value, ListNode<E> n) {
val = value;
next = n;
}
public void setNext(ListNode<E> n) {
next = n;
}
}
//reverse method
static ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode curNode = head;
ListNode preNode = null;
while (curNode != null) {
ListNode nextNode = curNode.next;
curNode.next = preNode;
preNode = curNode;
curNode = nextNode;
System.out.println("This is preNode: " + preNode.val);
}
return preNode;
}
//main method for the reverse execution
public static void main(String[] args) {
ReverseList rl = new ReverseList();
ReverseList.ListNode head = rl.new ListNode(1);
for (int i = 2; i <= 5; i++) {
head.next = rl.new ListNode(i);
head.next = head.next.next;
}
ListNode ln = reverseList(head);
//while not null it will point to next address
while (ln.next != null) {
System.out.println(ln.val);
ln = ln.next;
}
}
}
解决方案
推荐阅读
- svg - 在没有inkscape的情况下缩放svg内容以适应页面大小(反之亦然)
- c# - gameObject.GetComponent
() vs. gameObject.rigidbody - python - 2 我的烧瓶应用程序的独立登录系统 - 登录最佳实践
- python - 如何更快地将 json 数据加载到表中 django
- django - 如果 request.method == "POST" 返回 false
- javascript - 如何在地图内单独更改单选按钮状态?
- python - 将字典的值转换为字符串
- json - 如何将 JSON API 响应中的值正确设置到 Google 电子表格中
- python - 如何有效地更改矩阵/嵌套列表中的条目?
- python - Python - 如何将数据框中的每日值与字典中的每小时百分比相乘以获取具有每小时值的数据框