Write a function to delete the second last node of unsorted singly linked list
Question : You have an unsorted singly linked list with a head pointer and NO tail pointer and NO sentinel nodes. Write a function to delete the second last node of the list. In case the linked list has only one or less
nodes, the function should indicate failure, otherwise the function should
indicate success (and modify the original list). NOTE:
we do not know the total nodes in the list in advance. If you use any helper functions then
implement them also
SOLUTION
template <class type>
bool LinkedList<type>::DeleteSecondLastNode()
{
if
(!head && !head->next) //checking
if the list is empty or has only one node
return
false;
//find
the second last node
node
*curr = head;
node
*prev = NULL;
while(curr->next->next)
{
prev
= curr;
curr
= curr->next;
}
//check
if head is deleted or if it is the general case
if
(head = = curr)
head
= head->next;
else
prev->next
= curr->next;
delete
curr;
return
true;
}
Comments
Post a Comment