Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to front of linked list

I am confused as to how to add to the front of the 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 cycle. How do I avoid that?

I have a LinkedList class which holds the front Node, in a variable called front. I have a Node class within this LinkedList class.

Any help would be appreciated. Thank you.

like image 836
Catie Avatar asked Feb 03 '11 05:02

Catie


People also ask

Can you add to the front of a linked list?

This article shows how to add an element to the front of LinkedList in Java. Allocate the memory to a new node. Put in the element to be inserted in the allocated node. Make the next of the new node as the head.

How do you add an item to the front of a linked list in Java?

The java. util. LinkedList. addFirst() method in Java is used to insert a specific element at the beginning of a LinkedList.

What is the front of a linked list?

Each element in a linked list is called a node. A single node contains data and a pointer to the next node which helps in maintaining the structure of the list. The first node is called the head; it points to the first node of the list and helps us access every other element in the list.


2 Answers

Don't you have access to "Next" node ?

In that 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 {
    public Node next;
    private String _val;

    public Node(String val) {
        _val = val;
    }
}
like image 157
Jeff Avatar answered Sep 19 '22 00:09

Jeff


I'm assuming that the Node constructor takes a next pointer as its 2nd argument, in which case I don't see anything obvious wrong with this code. This really sounds like a homework question. If it is, you should tag it as such.

like image 21
takteek Avatar answered Sep 22 '22 00:09

takteek