【问题标题】:Creating a linked list and a few methods from scratch从头开始创建链表和一些方法
【发布时间】:2020-07-03 16:47:43
【问题描述】:

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

类 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); */

【问题讨论】:

  • 请编辑您的问题以包含您在运行程序时得到的确切错误消息和堆栈跟踪。

标签: linked-list


【解决方案1】:

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

【讨论】:

  • 谢谢,我给val赋值了,但是还是有运行时错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 2021-04-12
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多