This is a much simpler solution. Just one while
loop, and one if
statement.
node *detach(node *&l)
{
node **p=&l;
while ( (*p) && (*p)->next)
{
if ( (*p)->val > (*p)->next->val)
{
node *q=(*p)->next;
(*p)->next=(*p)->next->next;
return q;
}
p= &(*p)->next;
}
return NULL;
}
Now, with that out of the way, I think I'll just add a little bit of an explanation of how this works.
Let's start by looking at the basic loop for traversing a linked list:
node *p;
for (p=head; p; p=p->next)
{
;
}
That's as simple as it gets. You carry a pointer, and advance it to each element in the list. This is the first example in every textbook.
Now, let's take one step back. Suppose that instead of carrying a pointer to each node, how about carrying a pointer to that pointer?
What do I mean by that: a pointer to each element in the link list comes from one of two places: it's either the head
pointer, or the next
pointer from the previous node.
So, let's begin our adventure by taking the pointer to the head
:
node **p=&head;
That's a start. The next step is to advance this pointer to point to the next
for all remaining elements in the link list. So, we end up with something that looks like this:
for (node **p=&head; *p; p=&(*p)->next)
{
}
Inside the body of this for
loop, the expression "*p
" is logically equivalent to plain p
in the first, simple loop that uses a plain pointer.
Take a few moments to wrap you brain around this loop, and do not proceed further until you understand exactly how it works.
.
.
.
Now, go back to my initial answer, and you should be able to figure out how it works. It just so happens that when I wrote my answer I felt like using a while
loop, but it could simply be this exact for
loop, instead.
while
statement. Exactly oneif
statement. Nothing remotely like this extraprev
pointer. Should only be one pointer. If whatever you come up with has morewhile
orif
statements, or uses more than one pointer variable (except for the head pointer, which you calll
), it'll be wrong. – Splendiferousnode *&l
is a sign something very odd is going on here. When using pointers it's usuallynode** l
, and when using references there's no need for pointers at all. – Forrestforresteris_sorted_until
or previous one. – Camelopardusis_sorted_until
? – Calestastd::is_sorted_until
(even if not directly applicable as you have an own hand written list without iterator). – Camelopardus{ 10, 25, 20, 30 }
, is20
or25
out of order? – Adaptable1 6 4 10
, do you remove4
and get1 6 10
which is valid or you remove6
and get1 4 10
which is also valid? If you have1 6 4 5
, then obviously,6
need to be removed. – AndrogenT*&
. – Leatherjacketif
because once you find an out-of-order item, you need to decide if that item or the previous one need to be removed (see my examples in a previous comment) – Androgen