简体   繁体   English

如何在链表中最后插入元素

[英]how to insert element at last in linked list

I have to implement insertAtLast() in a linked list. 我必须在链接列表中实现insertAtLast()

I am getting a Null Pointer Exception in the code that i have written for insertAtLast() . 我在为insertAtLast()编写的代码中遇到了空指针异常。 Its maybe because I am Accessing it wrong. 可能是因为我访问错误。

How can I access it correctly and make the insertion too? 如何正确访问它并进行插入?

class myLinkedList {
private static class Node 
{
    private int data; 
    private Node next;

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

private Node head;

// Constructs an empty list
public myLinkedList() 
{
    head = null; 
}

// Returns true if the list is empty otherwise returns false
public boolean isEmpty() 
{
    return (head == null); 
}

// Inserts a new node at the beginning of this list.    
public void insertAtBeginning(int element) 
{
    head = new Node(element, head); 
}

// Returns the first element in the list.
public int getFirstElement() 
{
    if(head == null) 
    {
        System.out.println("Empty linked list"); 
        throw new IndexOutOfBoundsException();
    }
    return head.data; 
}

// Removes the first node in the list.
public int removeFirstNode() 
{ 
    int tmp = getFirstElement(); 
    head = head.next;
    return tmp;
}

// Empties linked list 
public void clear() 
{
    head = null; 
}

// Returns the length of the linked list
public static int LLlength(Node head)
{ 
    int length = 0;
    Node currentNode = head; 

    while(currentNode != null)
    {
        length++;
        currentNode = currentNode.next; 
    }
    return length; 
}

// Displays the linked list elements
public static void display(Node head)
{ 
    if(head == null) 
    {
        System.out.println("Empty linked list");
        throw new IndexOutOfBoundsException(); 
    }

    Node currentNode = head; 

    while(currentNode != null)
    {
        System.out.print(currentNode.data+" ");
        currentNode = currentNode.next; 
    }
    System.out.println();
}

// Displays the linked list elements in reverse order 
public static void displayReverse(Node head)
{
    if(head == null){} 
    else
    {
        Node currentNode = head; 
        displayReverse(currentNode.next); 
        System.out.print(currentNode.data+" ");
    } 
}
//Displays the linked list's last element
public static int getLastElement(Node head)
{
    Node currentNode = head; 

    while(currentNode.next != null)
    {
        currentNode = currentNode.next; 
    }
    return currentNode.data;
}
public static void insertAtLast(Node head,int element)
{
    Node newNode=null;
    newNode.data = element;
    newNode.next = null;
    while(head.next != null)
    {
        head = head.next; 
    }
    head = newNode;
    //return head;

}

//Tells if a sepeific element is in the Linked List or not
public static boolean searchFor(Node head, int element)
{
    Node currentNode = head; 
    boolean flag = false;
    while(currentNode != null)
    {
        if (currentNode.data == element)
        {
            flag = true;
            break;
        } 
        currentNode = currentNode.next;
    }
    return flag;
}

} 

Look at how your declaring the node object newNode . 看一下如何声明节点对象newNode You're setting it equal to null instead of instantiating it to an actual object. 您将其设置为等于null,而不是将其实例化为实际对象。 Remember that null means an empty reference. 请记住, null表示空引用。 Therefore, the next two lines of code will give you an error because you're trying to access member variables of "nothing". 因此,接下来的两行代码将给您一个错误,因为您尝试访问“ nothing”成员变量。 Since you have a Node class and constructor, use that instead of what you're doing now. 由于您具有Node类和构造函数,因此请使用它而不是现在执行的操作。 Lastly, use a temp variable that points to head and use that temp pointer to traverse through the node. 最后,使用指向头的temp变量,并使用该temp指针遍历该节点。 Because in what you had before, you would set the head to point to the new object in the linked list, which is the last element rather than the first, 因为在以前的操作中,您需要将头设置为指向链表中的新对象,该对象是最后一个元素而不是第一个元素,

public static void insertAtLast(Node head,int element)
{
    Node newNode= new Node(element,null);
    Node temp = head;
    while(temp.next != null)
    {
        temp = temp.next; 
    }
    temp.next = newNode;
    //return head;

}

there exists three troubles in your insertAtLast method. 您的insertAtLast方法中存在三个麻烦。


  1. Node newNode=null; 节点newNode = null; the newNode object is a null reference it don't reference a object of Node , you may change it into Node newNode = new Node(value,null) newNode对象是一个空引用,它不引用Node对象 ,您可以将其更改为Node newNode = new Node(value,null)
  2. after your while loop the head will make a reference with the last Node object, your works will only make head make a reference with a new Node object, it make no effect to the list self, for this new object have nothing with list. 在您的while循环之后 ,头部将对最后一个Node对象进行引用,您的工作将仅使头部对一个新的Node对象进行引用, 对列表自身无效 ,因为此新对象与列表无关。
  3. after this method, the head will reference a new object of Node rather than the first of the List. 使用此方法后,头将引用Node的新对象,而不是List的第一个对象。

an alternative solution : 替代解决方案:

public static void insertAtLast(Node head,int element)
{
   Node newNode=new Node(0,null);
   newNode.data = element;
   newNode.next = null;
   Node temp = head;
   while(temp.next != null)
   {
       temp = temp.next; 
   }
   temp.next = newNode;
  //return head;
}

First of all, why are a few of your methods static ? 首先,为什么您的一些方法是static They make sense to be a class method rather than static ones. 将它们作为类方法而不是static方法是有意义的。

If you want to support adding to the end of a linked list, I would suggest you keep track of the tail of your list. 如果你想支持添加到链接列表的末尾,我会建议你跟踪的tail你的列表中。 Right now your insertAtLast is O(n) and you can easily change that to O(1) by storing a pointer to the end of your linked list. 现在,您的insertAtLastO(n) ,您可以通过存储指向链表末尾的指针来轻松地将其更改为O(1)

It will add to the complexity of many other methods though. 但是,这将增加许多其他方法的复杂性。 So you might have to update the other ones if you decide to go with a tail pointer. 因此,如果决定使用tail指针,则可能必须更新其他指针。 I'm not going to to the details of your other methods but only give you what your non-static insertAtLast would look like if you had a tail pointer. 我不打算介绍其他方法的详细信息,而只是提供给您具有tail指针的非静态 insertAtLast外观。

public void insertAtLast(int element)
{
    Node newNode = new Node(element,null);

    if (head == null){ // you need to check for head, it may be null
       head = newNode;
    }

    if (tail == null){ // also, maybe there is no tail currently.
       tail = newNode;
       return;
    }

    //there is an existing tail, update it
    tail.next = newNode;
    tail = newNode;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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