Input Format:
The first line of input contains an integer , denoting the number of elements in the linked list.
The next lines contain an integer each in a new line, denoting the elements of the linked list in the order.
The last line contains an integer denoting the position of the node that has to be deleted form the linked list.
Sample Input
8 // Number of element
20
6
2
19
7
4
15
9
3 // position to remove
Sample Output
20 6 2 7 4 15 9
Solution:
import mathimport osimport randomimport reimport sysclass SinglyLinkedListNode:def __init__(self, node_data):self.data = node_dataself.next = Noneclass SinglyLinkedList:def __init__(self):self.head = Noneself.tail = Nonedef insert_node(self, node_data):node = SinglyLinkedListNode(node_data)if not self.head:self.head = nodeelse:self.tail.next = nodeself.tail = nodedef print_singly_linked_list(node, sep, fptr):while node:fptr.write(str(node.data))node = node.nextif node:fptr.write(sep)# Complete the deleteNode function below.## For your reference:## SinglyLinkedListNode:# int data# SinglyLinkedListNode next##def deleteNode(head, position):if(head==None):returnelse:if(position!=0):temp=headi=0while(i<position):pre=temptemp=temp.nexti+=1pre.next=temp.nextreturn headelse:return head.nextif __name__ == '__main__':fptr = open(os.environ['OUTPUT_PATH'], 'w')llist_count = int(input())llist = SinglyLinkedList()for _ in range(llist_count):llist_item = int(input())llist.insert_node(llist_item)position = int(input())llist1 = deleteNode(llist.head, position)print_singly_linked_list(llist1, ' ', fptr)fptr.write('\n')fptr.close()
0 Comments