linked-list - 从头开始创建链表和一些方法
问题描述
我正在尝试创建一个链接列表和一些方法,但是当我尝试运行它时出现运行时错误。
类 MyLinkedList {
public class Node{
int val;
Node next;
public Node(int x){
this.val = x;
}
}
private Node head;
private int size;
/** Initialize your data structure here. */
public MyLinkedList() {
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
if(index >= size) return -1;
Node current = head;
int position = 0;
while(position < index){
current = current.next;
position++;
}
return current.val;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
public void addAtHead(int val) {
Node nody = new Node(val);
nody.next = head;
size++;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
Node current = head;
while(current.next != null){
current = current.next;
}
current.next = new Node(val);
size++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void addAtIndex(int index, int val) {
if(index > size) return;
if(index == size){
addAtTail(val);
}
if(index == 0){
addAtHead(val);
}
int position = 0;
Node current = head;
Node nody = new Node(val);
while(position < index-1){
current = current.next;
position++;
}
nody.next = current.next;
current.next = nody;
size++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if(index >= size){
return;
}
if(index == 0){
head = head.next;
}
Node current = head;
int position = 0;
while(position< index-1){
current = current.next;
position++;
}
current.next = current.next.next;
size--;
}
}
/**
- 您的 MyLinkedList 对象将被实例化并按如下方式调用:
- MyLinkedList obj = new MyLinkedList();
- int param_1 = obj.get(index);
- obj.addAtHead(val);
- obj.addAtTail(val);
- obj.addAtIndex(index,val);
- obj.deleteAtIndex(index); */
解决方案
在Node
您的构造函数中,将字段分配val
给自身(null),而不是分配构造函数参数。
推荐阅读
- cognos - 属于 Cognos 中特定组的用户列表
- swift - NavigationLink 绑定问题
- ios - 如何为 iPhone 8 屏幕与 iPhone X 及更高版本的底部锚点设置不同的常量?
- java - 以编程方式添加 imageview 约束问题
- python - 如何将(纬度,经度)坐标转换为 tkinter 画布的坐标
- python-3.x - 如何使用 kivy 访问 iPhone 的位置?
- python - 我究竟做错了什么?“TypeError:不能将序列乘以‘str’类型的非整数”
- video - YOLO 用于视频(图像序列)
- php - PHP XPath 获取属性值的一部分
- json - 如何在 Python 中获取 JSON 值的索引?