﻿ Java exercises and solutions: singly linked list delete element

# Java exercises and solutions: singly linked list delete element

## Java OOP: singly linked list

### Delete element of singly linked list

Step 4: Delete an element of the singly linked list

To delete an element of the linked list, you need to consider the followings:

1. If the element to be deleted is the first element of the list and the list contains only one element, you only need to assign null to the pfirst and plast. If the element to be deleted is the first element of the list and the list contain more than one element, you need a temporary variable to point to the pfirst then move the pfirst to point to its next element and set the temporary variable to null.

2. If the element to be deleted is in the middle of the list, you need a traversing pointer(temp) to point to the element before the element to be deleted and a temporary pointer(del) to point to the element to be deleted. Then let the link of the traversing variable to point to the link of the temporary pointer. To handle situation where the element to be deleted is the last element of the list, you need to test whether the link of the temporary variable is null. If it is really null, you need to update the plast to point to the traversing pointer. Finally set the temporary variable to null.

// delete an item from the linked list
t public void delete(int pos)
{
if (countitem() > 0)
{ //make sure the list is not empty.
ListNode<T> temp,del;
if (pos== 1)
{//delete the first item
if(countitem()==1){ //The list contains only one item
pfirst=null;
plast=null;

}
else{ //The list contains more than one item
temp=pfirst;
pfirst=pfirst.next;
temp=null;
}
System.out.println("Deleted");

}

else if (pos > 1 && pos <=countitem())
{//delete middle item
temp=pfirst;
int i;
for(i=1;i<pos-1;i=i+1){temp=temp.next;} //move to the item staying before the target item to be deleted
del=temp.next; //target item to be deleted
temp.next=del.next;
if(del.next==null)plast=temp; //delete last item
del=null;
System.out.println("Deleted");

}

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

}

else System.out.println("No item found");

}

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.