Here is a function that takes a sorted linked list of integers and mutates it so that all duplicates are removed.
And this is the answer:
def remove_duplicates(lnk):
"""
>>> lnk = Link(1, Link(1, Link(1, Link(1, Link(5)))))
>>> unique = remove_duplicates(lnk)
>>> unique
Link(1, Link(5))
>>> lnk
Link(1, Link(5))
"""
-sharp Recursion solution
if lnk is Link.empty or lnk.rest is Link.empty:
return lnk
if lnk.first==lnk.second:
lnk.rest=lnk.rest.rest
remove_duplicates(lnk)
return lnk
else:
remove_duplicates(lnk.rest)
return lnk
But I want to know why the 4th line lnk.rest=lnk.rest.rest
couldn"t be lnk=lnk.rest
unique be Link (1, Link (5)
and lnk be Link (1, Link (5)
if I use lnk=lnk.rest
Is anyone could help me get out of it?