在不使用内置方法/导入util的情况下在java中创建链表

时间:2015-09-27 12:55:43

标签: java linked-list

  

问题是创建一个创建节点和链接的链接列表   他们应该有以下方法。

     
      
  • addfirst仅
  •   
  • addlast仅
  •   
  • 移除/删除
  •   
  • 在...之前和之后插入
  •   

我已经成功完成了下面的工作,但我似乎无法解决代码的问题。一段错误读取“LinkedList.java [line: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 个答案:

答案 0 :(得分:4)

给您错误的变量headnew Node(data, head) )指的是您所在的新变量head创造过程。添加this

可以解决此错误
Node head = new Node(data, this.head); 

或者,如果你试图创建一个新变量:

head = new Node(data, head);