简体   繁体   中英

Creating linked lists in java without using in-built methods/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...

I've managed to do the bit below but I can't seem to get what's wrong with the code. Piece of the error reads " LinkedList.java [line: 16] Error: variable head might not have been initialized "

/*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 + " ";
    }
}

The variable head that is giving you the error ( new Node(data, head) ) refers to the new variable head that you are in the process of creating. This error can be solved by adding this :

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

Or, if you're not trying to create a new variable:

head = new Node(data, head); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM