Today we are going to share a Python program to delete M nodes after N nodes. If you are a python beginner and want to start learning the python programming, then keep your close attention in this tutorial as I am going to share a Python program to delete M nodes after N nodes.
To increase your Python knowledge, practice all Python programs, here is a collection of 100+ Python problems with solutions.
Copy the below python program and execute it with the help of python compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to prit the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next def skipMdeleteN(self, M, N): curr = self.head # The main loop that traverses through the # whole list while(curr): # Skip M nodes for count in range(1, M): if curr is None: return curr = curr.next if curr is None : return # Start from next node and delete N nodes t = curr.next for count in range(1, N+1): if t is None: break t = t.next # Link the previous list with reamining nodes curr.next = t # Set Current pointer for next iteration curr = t # Driver program to test above function # Create following linked list # 1->2->3->4->5->6->7->8->9->10 llist = LinkedList() M = 2 N = 3 llist.push(10) llist.push(9) llist.push(8) llist.push(7) llist.push(6) llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print "M = %d, N = %d\nGiven Linked List is:" %(M, N) llist.printList() print llist.skipMdeleteN(M, N) print "\nLinked list after deletion is" llist.printList() |
M = 2, N = 3
Given Linked list is :
1 2 3 4 5 6 7 8 9 10
Linked list after deletion is :
1 2 6 7
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.