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 the linked list unchanged. The skip amount determines the amount to skip over. I want to change the linked list accordingly and then return the linked list with the modifications, not a list.
If you have a linked list 11 -> 12 -> 18 -> 20 -> 24 -> 32 -> 38 -> 44
and skip =2, then the linked list you return should be the following:
18 -> 32
If skip = 1, then the linked list you return should be the following:
12 -> 20 -> 32 -> 44
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def getNth(self, index):
current = self.head # Initialise temp
count = 0 # Index of current node
while (current):
if (count == index):
return current.data
count += 1
current = current.next
assert(false)
return 0;
if __name__=='__main__':
llist = LinkedList()
print("length of linked list")
length = int(input())
print("enter data for linked list")
for _ in range(length):
llist.push(int(input()));
print('skips:')
skip = int(input())+1
indexes = list(range(0,length,skip))
indexes.pop(0)
for n in reversed(indexes):
print(llist.getNth(n-1),"->",end='')
print("completed")
Approach:
1. We create a linkedlist taking input
2. We create a second list with indexes that need to be
printed
3. We print each of those indexes in reverse order to get the
required list.
Alternatively, you can save this newly created linkedlist by simply
creating a new object and pushing the data there.