package exercise.LinearTable.impl;
import exercise.LinearTable.LinearList;
public class SingleList{
Node head = null;//表头
public boolean isEmpty() {
int length = size();
if(length==0) {
return true;
}
return false;
}
public int size() {
int length = 0;
Node temp = head;
while(temp.next!=null) {
length++;
temp = temp.next;
}
return length;
}
public Object get(int index) {
Node temp = head;
int i = 1;
if(index == 0) {
return head;
}
while(temp.next!=null) {
if(index==i) {
return temp;
}
temp = temp.next;
i++;
}
return temp;
}
public int add(Object element) {
int i=0;
if(head.next==null) {
head.next = (Node) element;
return i;
}
//新建一个节点
Node newnode = new Node(element);
Node temp = head; //一个移动的指针(把头结点看做一个指向结点的指针)
while(temp.next != null){ //遍历单链表,直到遍历到最后一个则跳出循环。
temp = temp.next; //往后移一个结点,指向下一个结点。
}
temp.next = (Node) element; //temp为最后一个结点或者是头结点,将其next指向新结点
i++;
//链表为空
return i;
}
public void insert(int index, Node element) {
//首先需要判断指定位置是否合法,
if(index<1||index>size()){
System.out.println("插入位置不合法。");
return;
}
Node temp = (Node) get(index);
element.next = temp.next;
temp.next = element;
}
@Override
public Object remove(int index) {
//判断index是否合理
if(index<1 || index>size()){
System.out.println("给定的位置不合理");
return null;
}
Node temp = (Node) get(index-1);
temp = temp.next.next;
return temp;
}
public void tostring() {
Node temp = head;
while(temp.next!=null) {
System.out.print(" "+temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
SingleList s = new SingleList();
s.add("1");
s.add("1");
s.add("1");
s.add("1");
s.tostring();
}
}
class Node{
Node next = null;
Object data;
public Node(Object data) {
this.data = data;
}
}
请求大佬支援!!!单链表报错
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- V、D❧R 2019-12-10 17:47关注
你这个list 的初始head设置的是null,当他第一次调用add方法时, if(head.next==null) 这句要获得head的next属性,但是head为null,无法获得next属性,所以报了一个空指针异常
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?
- ¥15 c++头文件不能识别CDialog