Sample Input
3 // Number of element
16
13
7
1 // Value to be insert
2 // Position
Sample Output
16 13 1 7
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 insertNodeAtPosition function below.## For your reference:## SinglyLinkedListNode:# int data# SinglyLinkedListNode next##def insertNodeAtPosition(head, data, position):if (head==None):new=SinglyLinkedListNode(data)head=newelse:temp=headi=0while(i<position):pre=temptemp=temp.nexti+=1new=SinglyLinkedListNode(data)pre.next=newnew.next=tempreturn headif __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)data = int(input())position = int(input())llist_head = insertNodeAtPosition(llist.head, data, position)print_singly_linked_list(llist_head, ' ', fptr)fptr.write('\n')fptr.close()
0 Comments