有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中创建链表而不使用内置方法/importing util

The question is to create a linked list that creates nodes and links them and should have the following methods.

  • AddFirst
  • AddLast
  • Remove/Delete
  • Insert before and after...

我已经设法做到了下面的一点,但我似乎不知道代码出了什么问题。错误代码为“LinkedList.java[第16行] 错误:变量头可能尚未初始化“

/*Uses the node class to create a linked list of integer type 
 * nodes and stores them 
 */

public class LinkedList
{

    public Node head;

    public static void main(String [] args) {

    }

    //Methods adds a link to the head
    //Appends to the beginning of the list

    public void addFirst(int data) {
        Node head = new Node(data, head);
        //Because head is the pointer to the first node   

        // Traversing the list
        Node temp = head;
        while (temp != null) {
            temp = temp.next;
        }
    }

    //Adding at the end of the list

    public void addLast(int data) {
        if (head == null) {
            addFirst(data);
            //When the list is empty, i.e, head points to null
        } else {//When list is populated
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
                temp.next = new Node(data, null);
            }
        }
    }

    //To insert a new node after a given "key"
    //_data is the new node data 

    public void insAft(int _data, int key) {
        Node temp = head;
        while (temp != null && temp.data != key) {
            temp = temp.next;
        }
        if (temp != null) {
            temp.next = new Node(_data, temp.next);
        }
    }
}

/*Node class to create the node (object)
 * takes integer parameters
 */

class Node{

    public int data;
    Node next;

    public Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }

    public String toString() {
        return data + " ";
    }
}

共 (1) 个答案

  1. # 1 楼答案

    给出错误的变量headnew Node(data,head))指的是您正在创建的新变量head。此错误可以通过添加this来解决:

    Node head = new Node(data, this.head); 
    

    或者,如果您不是尝试创建新变量:

    head = new Node(data, head);