C# tutorial-delete item of circularly linked list |
|||||||||||||||||||||||||||
Delete item of circularly linked listStep 4: Delete an element of the circularly linked list To delete an element of the circularly 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 links. 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 link to point to the pfirst then move the pfirst to point to its next element and set the temporary link to null.
2. If the element to be deleted is in the middle of the list, you need a traversing link(temp) to point to the element before the element to be deleted and a temporary link(del) to point to the element to be deleted. Then let the next link of the traversing link to point to the next link of the temporary link. To handle situation where the element to be deleted is the last element of the list, you need to test whether the target item is equal to the plast. If it is really equal, you need to update the plast to point to the traversing link. Finally set the temporary link to null.
//C# code to delete an item of the circularly linked list public void delete(int pos) { int deleted = 1; if (pfirst != null) { //make sure the list is not empty. ListNode<T> tr, temp;
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 tr = pfirst; pfirst = pfirst.next; tr = null; } Console.WriteLine("Deleted");
}
else if (pos > 1 && pos <= countitem()) {//delete middle item tr = pfirst; int i; for (i = 1; i < pos - 1; i = i + 1) { tr = tr.next; } //move to the item staying before the target item to be deleted temp = tr.next; //target item to be deleted tr.next = temp.next; if (temp.next == null) plast = tr; //delete last item temp = null; Console.WriteLine("Deleted");
}
else { deleted = 0; Console.WriteLine("Invalid position!"); } if (deleted != 0 && plast != null) plast.next = pfirst; //keep the list circularly linked
}
else Console.WriteLine("No item found");
}
|
|||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||