remove 0 from linked list

Hello i want to delete 0 from the linked list
Last edited on
Go through the linked list.

Each time you find a zero node, update the previous node to point at the next node, and then delete the zero node.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <list>

int main()
{
   std::list<int> lst { 0, 1, 0, 0, 5, 0, 9 };

   for (const auto& itr : lst) { std::cout << itr << ' '; } std::cout << "\n\n";

   lst.remove_if([] (int n) { return n == 0; });

   for (const auto& itr : lst) { std::cout << itr << ' '; } std::cout << '\n';
}

0 1 0 0 5 0 9

1 5 9
reconnect the pointers around the items.
your delete should maybe be boolean (true: found and deleted something, false: not there nothing done)

to do that you generally need safe looks at one past here.

so your here pointer is at the first zero.
this is a special case, so you detect that (here == head of list).
tmp = head;
head = head ->next;
tmp->next = null;
deleteditemslist.insert(tmp); //save the memory to use on an insert later for efficiency

and now your list is
1 0 0 5 0 9
next time you call delete, here is 1 and head.
the head isnt the value you seek (0).
is head->next existing?
yes.
is head->next zero? yes (else move head +1 and repeat).
tmp = head->next. (tmp is first zero guy)
head->next = tmp->next. (list is now 10509)
tmp -> next = null; //don't allow tmp a door back into the list.
deleteditemslist.insert(tmp); //save the memory to use on an insert later for efficiency

and so on. end of the list also has a special case (just remove it and set previous pointer null).

if you don't care to keep the deleted list, just delete the memory of tmp instead.

once your delete item routine works, call it in a loop (remember that bool?) while its true, deleting zeros each time until none found and stop.
Topic archived. No new replies allowed.