﻿ Java exercises and solutions: add element to linked list

# Java exercises and solutions: add element to linked list

## Java OOP: singly linked list

### Add element to singly linked list

Step 3: Add an element to the linked list

To add an element to the linked list, you need to consider 4 things:

1. When the list is empty, to add a new element to the list, you only let the pfirst and plast point to the new item. We mark the null value of link of an element by crossed lines.

2.If the new element is to be added to the beginning of  the list, you will need to let the link of the new item points to the pfirst and then update the pfirst to point to the new item.

3. If the new element is to be added to the middle position of the list, you need to let a variable ta point to the position immediately before the position that the new element will be placed in.

4. If the new element is to be added to the last of the list, you need to let the link of the plast point to the new element then update the plast to point the new element.

// insert a new item to the linkedlist

public void insert(T val, int pos)
{
ListNode<T> newnode = new ListNode<T>(val);
//empty list
if (pfirst == null && plast == null)
{
newnode.next=null;
pfirst = newnode;
plast = newnode;
System.out.println("Inserted:"+newnode.val);
}
//Insert at the beginning of the list
else if (pos == 1)
{
newnode.next=pfirst;
pfirst=newnode;
System.out.println("Inserted:"+newnode.val);
}
//Insert in the middle of the list
else if (pos > 1 && pos < countitem())
{
ListNode<T> ta;
ta = pfirst;
for (int t = 1; t < pos-1; t = t + 1) { ta = ta.next; }
newnode.next = ta.next;
ta.next = newnode;
System.out.println("Inserted:"+newnode.val);
}
else if (pos == countitem() + 1)
{

newnode.next = null; //The next link of the item is null.
plast.next = newnode;
plast = newnode;
System.out.println("Inserted:"+newnode.val);

}
else System.out.println("Invalid position!");

}