Dole
Dole

Reputation: 339

Create new head for a list with data

Sorry for a noob question, but the syntax is a bit confusing here. I am asked to fill in the function to insert new element onto the front of a linked list. The code:

class LinkedList
{
    public LinkedList ()
    {
        this.head = null;
    }

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

    /* returns the first element of the list, assuming that the list is not empty */
    public int front ()
    {
        return head.data;
    }

    /* prints the list */
    public void print ()
    {
        System.out.print("(");
        for (ListNode i = head; i != null; i = i.next)
            System.out.print(i.data + " ");
        System.out.println(")");
    }

    /* inserts x into the beginning of the list */
    public void insertFront (int x)
    {
        /* FILL HERE!!! */
    }
}

The code for the nodes:

class ListNode
{
    public ListNode()
    {
        this.data = 0;
        this.next = null;
    }

    public int data;
    public ListNode next;
}

I figured I need to create a new node, assign the value of the current head for the next operator, and set the value equal to x. And then finally set the node to be the new head.

Can someone show me how to perform those basic commands.

Upvotes: 0

Views: 835

Answers (1)

Zabuzard
Zabuzard

Reputation: 25943

Just declare your new element as head and let it point to the previous head, which is now the second element.

/* inserts x into the beginning of the list */
public void insertFront(int x)
{
    // Temporarily memorize previous head
    ListNode previousHead = this.head;

    // Create the new head element
    ListNode nextHead = new ListNode();
    nextHead.data = x;
    // Let it point to the previous element which is now the second element
    nextHead.next = previousHead;

    // Update the head reference to the new head
    this.head = nextHead;
}

Here is a small illustration of the process:

LinkedList structure, inserting at front

Upvotes: 1

Related Questions