Add to list of linked lists

I am confused about how to add to the front of a linked list.

/**
* data is added to the front of the list
* @modifies this
* @ffects 2-->4-->6 becomes data-->2-->4-->6
*/
public void insert(E data) {
    if (front == null) 
        front = new Node(data, null);
    else {
        Node temp = new Node(data, front);
        front = temp;
    }
}

This creates a loop. How to avoid this?

I have a LinkedList class that contains the front of a Node, in a variable called the front. I have a Node class in this LinkedList class.

Any help would be greatly appreciated. Thank.

+3
source share
6 answers

You do not have access to the "Next" node?

In this case

 public void insert(E data)
{
  if (front == null) 
  { 
     front = new Node(data, null);
  }
  else 
  {
     Node temp = new Node(data, null);
     temp.next = front;
     front = temp;
  }
}

-

 class LinkedList
{
    Node front;
    LinkedList() { front = null; }
    public void AddToFront(String v)
    {
        if (front == null)
        {
            front = new Node(v);
        }
        else 
        {
            Node n = new Node(v);
            n.next = front;
            front = n;
        }

    }


}

class Node 
{
    private String _val;
    public Node(String val) 
    {
        _val = val;
    }

    public Node next;
}
+6
source

Thanks to my limited knowledge of the linked list, I would take a chance:

Node temp = new Node(data);
temp.next = front;
front = temp;

You might want to wait for someone to confirm this.

+2
source

, Node , . . , .

+2

. ?

, , , , .

, , , . , / - , .

, /... Node , , .

+1
source

Add a new node, and if the current head is not zero, then point the current head to the newly created node as the next node.

Node insert(Node head,int x) {
    Node node = new Node();
    node.data = x;
    if(head != null) {
       node.next = head;}
    return node;
}
0
source

This is my implementation of inserting a node at the beginning or at the beginning of a linked list in Java.

void insertAtHead(Object data){
    if(head==null) {
        head = new Node(data);
    }
    Node tempNode = new Node(data);
    Node currentNode = head;
    tempNode.setNext(currentNode.getNext());
    head.setNext(tempNode);
    incrementCounter();
}
0
source

Source: https://habr.com/ru/post/1789664/


All Articles