In: Computer Science
In python I want to create a singular function that takes two parameters 'head; and 'skip'.
Head is a linked list. Skip is a non negative value. If skip is zero it should return head unchanged. The skip amount determines the amount to skip over. I want to change the linked list accordingly.
If you have a linked list 11 -> 12 -> 18 -> 20 -> 24 -> 32 -> 38 -> 44
and skip =2, then you should return the following:
18 -> 32
If skip = 1, then you should return the following:
12 -> 20 -> 32 -> 44
class ListNode:
""" Models a single node in a singly-linked list. Has no methods, other
than the constructor.
"""
def __init__(self, val):
""" Constructs the object; caller must pass a value, which will be
stored in the 'val' field.
"""
self.val = val
self.next = None
def __str__(self):
vals = []
objs = set()
curr = self
while curr is not None:
curr_str = str(curr.val)
if curr in objs:
vals.append(
"{} -> ... (to infinity and beyond)".format(curr_str))
break
else:
vals.append(curr_str)
objs.add(curr)
curr = curr.next
return " -> ".join(vals)
def accordion_n(head,skip_amt):
if skip_amt<0:
print("INVALID... skip amount should be non-negative")
elif skip_amt==0:
return head
else:
op=[]
curr_skip=0
for i in range(len(head)):
if curr_skip==2:
op.append(head[i])
curr_skip=0
else:
curr_skip+=1
return " -> ".join(op)
if __name__=="__main__":
n=int(input("Enter number of nodes in linked list: "))
l=[]
a=int(input())
l.append(ListNode(a))
for i in range(1,n):
a=int(input())
l.append(ListNode(a))
l[i-1].next=l[i]
x=str(l[0])
y = x.split(" -> ")
#Test Case 1
skip_amt=int(input("Enter skip amount: "))
print("Given List:",str(l[0]))
print("Skip amount:",skip_amt)
ans=accordion_n(y,skip_amt)
print("Output List:",ans)
#SAMPLE OUTPUT
PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT
SECTION