首页 > 解决方案 > 从头开始创建链表和一些方法

问题描述

我正在尝试创建一个链接列表和一些方法,但是当我尝试运行它时出现运行时错误。

类 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--;
    
    
}

}

/**

标签: linked-list

解决方案


Node您的构造函数中,将字段分配val给自身(null),而不是分配构造函数参数。


推荐阅读